lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I'm sure this has been discussed before, but I would be interested in others thoughts and/or comments. Since in Lua all functions are really anonymous, recursion seems to be fragile. Consider this code:

function fact(n)
	if n == 0 then return 1 end
	return n * fact(n-1)
end

fact1 = fact; fact = nil
fact1(10)

This breaks (of course), since the function tries to call fact() instead of fact1() when it recurses. Of course the obvious answer is "well dont do that!" but if i'm creating library routines for use by others I don't like having to publish lots of "do and dont" caveats; it's too fragile.

I can only think of two solutions, and I don't really like either:
1. Extend the language with some kind of magic "self" name so that the function can reference itself regardless of where it is stored (a kind of function-level "this" pointer I guess). I can almost SEE Roberto getting mad at such an idea (I know I would), and besides it doesnt help with mutually-recursive functions.

2. Wrap the function in a closure that contains a reference to itself and recurse using the closure. Something like this:

do
	local function f1(n)
		if n == 0 then return 1 end
		return n * f1(n-1)
	end
	fact = f1
end

This works but it takes the performance hit of the closure just to get the recursion.

Comments anyone? Am I missing something obvious here?

--Tim