Why doesn't this recursive function work?

After fighting it for HOURS, I finally narrowed down my issue. I made a very simple version here to explain the problem.

function thing()
	local majig = math.random(1, 3)
	if majig == 3 then
		thing()
	else
		return majig
	end
end


while wait(1) do
	local asdf = thing()
	print(asdf)
end

When it gets a number 1 or 2, it returns that number, and prints it. But, when it’s 3, rather than call the function again, it seems to instead just return “nil”, and that’s what it prints. I understand that since I’m setting it equal to a variable, and since it doesn’t return anything, it would make sense that it gets “nil”, but shouldn’t it not have ended yet and continued on with the next function recursively since it was called?
Someone explain?

function thing()
	local majig = math.random(1, 3)
	if majig == 3 then
		return thing()
	else
		return majig
	end
end


while wait(1) do
	local asdf = thing()
	print(asdf)
end

return the function, im pretty sure it works by getting the returned value from the function being called.

1 Like

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