lua-users home
lua-l archive

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


2018-01-09 22:09 GMT+02:00 dyngeccetor8 <dyngeccetor8@disroot.org>:

>> I wrote a simple file "essai.lua" containing :
>>
>> --
>> function essai1()
>>   print(debug.getinfo(1,"n").name)
>> end
>>
>> essai1()
>> --
>>
>> When I do
>>
>> $ lua essai.lua
>> essai1
>>
>> This is logical to me.
>>
>> Now, if I start lua and *copy and paste* the same code as in "essai.lua", I have
>>
>> $ lua
>> Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
>>> function essai1()
>>>>   print(debug.getinfo(1,"n").name)
>>>> end
>>>
>>> essai1()
>> nil
>>
>> [...]
>>
>> Philippe
>
> Wrap in do-end block. (I dont know why it works either.)
>
>   Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
>   > function essai1()
>   >>   print(debug.getinfo(1,"n").name)
>   >> end
>   >
>   > essai1()
>   nil
>   > do
>   >> function essai1()
>   >>   print(debug.getinfo(1,"n").name)
>   >> end
>   >>
>   >> essai1()
>   >> end
>   essai1

This is a very interesting question, especially to someone that
has contributed a Rock [1] which heavily relies on debug.getinfo.

debug.getinfo(1,"n").name is an attempt to find a local name
for the running function. It does not as a general rule look
for global names. So the mystery is not why you failed to get
the name when you defined the function in interactive mode,
it is why you did get it when running it from a file.

The only explanation that I can think of is based on chunks.

A chunk is a portion of code that is offered as a whole to
the Lua interpreter to be translated to bytecode. For example:
  1. A line that you type in interactive mode (or several lines,
if it is waiting for "end","]]" etc) is one chunk.
  2. A file that you execute with "dofile" or load with "loadfile"
is one chunk.
  3. The string that you pass to "load" is one chunk.

Now if you do what you did the first time or what Martin did,
the definition of the function and its execution happen in
the same chunk. The code would still have worked if you
defined 'essai1" as a local function. But in interactive mode,
if you define "essa1" on one line and call it on another, that's
two chunks and if "essa1" was local, you can't see it any more.

So what we observe is that global names defined in the same
chunk are taken into account by debug.getinfo (you might
say they have honorary local status) but global names defined
elsewhere are not.

Where does that status come from? I think it may have something
to do with _ENV. Whenever you compile a chunk, you get a new
upvalue named _ENV. The outside _ENV is not visible. (Its
contents is, unless you yourself change it, because it starts
off as equal to the old one.)

At this stage it is only a guess. One will have to make a bytecode
listing (with "luac -ll") and maybe even read the Lua source to
make sure.

[1] luarocks install ihelp