Is there a recursion limit?

How many times can a function call itself before it’s stopped or is there no limit?
eg:

local i = 1

function recurse()
	wait()
	print(i)
	i += 1
	recurse()
end

recurse()

I would imagine there is a limit but not one reached in normal code

yes i spent my time getting it :man_shrugging::man_facepalming:

I tried it on a server script and the same results

Watched anime while I waited

1 Like

i changed the wait() to game:GetService("RunService").RenderStepped:Wait() so it runs a bit faster

1 Like

Luau’s limits are officially documented here.

  • Stack depth: 20000 Lua calls per Lua thread, 200 C calls per C thread (e.g. coroutine.resume / pcall nesting is limited to 200)

Here’s a quicker way to cause the error.

local function recurse(count)
	count += 1
	print(count)
	if count % 1000 == 0 then task.wait() end
	recurse(count)
end

recurse(0)

2 Likes

Honestly at only 20,000, you don’t really even need to wait.

Without a yield you’ll encounter an exhaustion error instead.

2 Likes

this code here seems to not have a limit:

local function recursive(amt)
	print(amt)
	task.delay(game:GetService("RunService").RenderStepped:Wait(), recursive, amt + 1)
end
recursive(0)

anyone seeing any problems?