[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: local pre-declarations
- From: Gabor Grothendieck <ggrothendieck@...>
- Date: Wed, 1 Sep 2004 13:02:43 +0000 (UTC)
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()
: 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?
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