Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
adoman 0
8 years ago

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

Log in to vote
1
Answered by
Necrorave 560 Moderation Voter
8 years ago

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.

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)? adoman 0 — 8y
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 Necrorave 560 — 8y
Ad

Answer this question