Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Is calling a function inside of a while loop a good choice?

I have called functions in loops many times and I was wondering if it the right method?

I believe that this is a poor way of calling a function from a loop:

local function run(number)
	if (number == 1) then
	print("the number is " .. number)
end

while script.Parent.Disabled == false do
	local randomNum = math.random(1, 4)
	wait()
	run(randomNum)
end

I have done this before but I am not sure if it is reliable enough to use in a popular published game:

functionRunning= false

local function run(number)
	functionRunning = true

	if (number == 1) then
	print("the number is " .. number)

	functionRunning = false
end

while loopRunning == false do
	local randomNum = math.random(1, 4)
	wait()
	run(randomNum)
end

Please let me know if there is any better way to call a function repeatedly from a loop. I have real code (not just examples) if that is needed to find the answer to this question please let me know and I could also post that here.

1 answer

It all depends on your logic. Running a function inside of a loop is not a bad thing. As long as you keep in mind that the loop will not continue until the function ends.

Always double check to make sure your loops and logic are correct to prevent crashes or any other game breaking errors.

If you have any other questions, let me know.

2 comments

0

Alright so using the second shown method with the functionRunning boolean should always stop the while loop from running while that function is active (meaning that no extra function calls will sneak in)?

0

Actually, while adding a "Debounce" is good, it is not needed in your case. Since it will run through the entire function before it continues through the loop

This discussion is preserved as it was. New answers, comments, and votes are closed.