Why does this stack overflow after 1000s of tries?

--!strict


-- SERVICES
local ReplicatedStorage = game:GetService("ReplicatedStorage")


-- VARIABLES
local Events = ReplicatedStorage.Events

local gotAnswered: boolean?


-- FUNCTIONS
local function gameOver()
    
    task.wait(1)
    
    gotAnswered = nil
    
    activeGame()
end


function activeGame()

    local notAnswered = true

    for Timer = 10, 1, -1 do

        if gotAnswered then

            gameOver()

            notAnswered = false
            break
        end

        task.wait(1)
    end

    if notAnswered then

        gameOver()
    end
end


Events.Answered.Event:Connect(function(Player: Player)
    
    gotAnswered = true
end)


activeGame()

This is a bare-bones version of it’s actual use which is for a Trivia system I need to go on infinitely, however when I ran it after about 5000+ iterations eventually it would just stop, and the error log would look something like this:


From what I’ve seen it’s because it goes on forever, but I need it to go on forever so how would I go about doing that?

I thought of cloning the script and delete the current one but I feel that is wrong and there is a better solution

You are just calling the functions over and over again, resulting in infinite recursion. You could just use a while true loop in your case, and not call activeGame again in gameOver, nor reset gotAnswered because it gets reset at every iteration.

local function gameOver()
    task.wait(1)
end


function activeGame()
     while true do
        gotAnswered = nil
        
        local notAnswered = true
        for Timer = 10, 1, -1 do
            if gotAnswered then
                notAnswered = false
                break
            end
            task.wait(1)
        end
        
        -- do stuff here when game ends, ex.: call gameOver()
        task.wait(1)
    end
end

Events.Answered.Event:Connect(function(Player: Player)
    gotAnswered = true
end)

activeGame()
1 Like

thx lavasance i got this error too

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.