Skip to content

Infinite loops

Shararvev edited this page Sep 24, 2021 · 3 revisions

Эта страница доступна на Русском

Sometimes you may need to make a looped round-trip train, or a repeating mechanism that starts its movement again at the end of the cycle. The following example will cause the game will freeze due to a recursive call that falls into an infinite loop.

	local button = controller:GetMetaTarget("start_button_no")
	button.OnPressed = function(ent, activator)
		print(activator, "just pressed", ent)
		button:Fire("Press") -- FAIL! infinite loop
	end
	button:Fire("Press") -- for test only

Use the third argument delay in the Entity:Fire method to add a delay and safely handle such cases. I will clarify that the sample itself does not make sense, it is only for demonstrating recursion.

	local button = controller:GetMetaTarget("start_button_no")
	button.OnPressed = function(ent, activator)
		print(activator, "just pressed", ent)
		button:Fire("Press", nil, 0.01) -- recurse, but not fail (anyway, for what?)
	end
	button:Fire("Press") -- for test only

Clone this wiki locally