lua-users home
lua-l archive

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


Asko Kauppi <asko.kauppi <at> sci.fi> writes:

: 
: Is there a simple "better way" to this?
: 
: When I have local functions that rely on each other, and the one used 
: cannot be defined before the usage place (it's used at runtime, anyhow) 
: I do this:
: 
: 	local func2
: 
: 	local function func1()
: 		...
: 		func2()
: 		...
: 	end
: 
: 	...
: 	--local
: 	function func2()
: 		...
: 
: This is the "right" way to do it, right?
: 
: I don't like it too much, since 'func2' mustn't have "local" before it. 
:   If it does (which happens easily) the value within 'func1' will be 
: 'nil', and things fall apart.  Of course, this is not noted until 
: runtime, so bugs easily lurk in.
: 
: Also, the latter definition of 'func2' looks too much of a global.
: 
: Good ideas, anyone?
: 
: -ak
:

If the objective here is to get rid of the declaration then the utility
function Recall defined in the first line below would allow you to do it.
It calls the function n levels up on the stack so if f calls g and
g which calls Recall(2) then Recall(2) returns the function f.

Recall = function(n) return debug.getinfo((n or 1)+1,"f").func end
local g = function(x) 
   if (x > 0) then return x + Recall(2)(x-1) else return 0 end end
local f = function(x) 
   if (x > 0) then return x + g(x-1) else return 0 end end
print(f(3))