[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Using debug to find the enclosing function
- From: Roberto Ierusalimschy <roberto@...>
- Date: Thu, 10 Dec 2020 11:20:13 -0300
> Consider the following:
>
> function foo ()
> function bar () end
> end
>
> Is there a precise way, at runtime, to find the function that encloses bar?
>
> It appears the best (but imprecise) approximation is to use
> debug.getinfo() and then compare the values of linedefined and
> lastlinedefined for each function.
>
> (This approximation would be incorrect (or inconclusive) in the
> (possibly rare) circumstance where two functions were completely
> defined on the same line(s).)
Why do you need this information?
In Lua, functions are not a thing. What is a thing are closures,
dynamically created instances of function prototypes. So, a program can
have several instances of "foo" and several instances of "bar", or even
some instances of "bar" without any instance of "foo".
In particular, the notion of "the function A that encloses another
function B" is actually between closures and, in particular, A
may not necessarily exist during all existence of B:
function foo ()
function bar () end
end
-- foo refers to 1 instance of "foo", there are no "bar"s
foo()
-- foo refers to 1 instance of "foo" and bar to 1 instance of "bar"
foo = nil
-- bar refers to 1 instance of "bar", there are no "foo"s
-- Roberto