How does debug.traceback get its information?

Viewed 2252

With the below code from the Lua demo page, I was trying to get the name of the function being pcalled.

function test()
    local info = debug.getinfo(1);

    for k, v in pairs(info) do
        print(k, v);
    end;
end;

pcall(function()
    test();
end);

This was a success, as I received the following output, containing the name:

source  =input
func    function: 0x25a1830
nparams 0
short_src   input
isvararg    false
name    test
namewhat    global
istailcall  false
linedefined 1
lastlinedefined 7
nups    1
currentline 2
what    Lua

If I change the code to the following, I no longer get that information:

function test()
    local info = debug.getinfo(1);

    for k, v in pairs(info) do
        print(k, v);
    end;
end;

pcall(test);

The output is as follows:

func    function: 0x21ee790
linedefined 1
nups    1
short_src   input
namewhat    
lastlinedefined 7
isvararg    false
istailcall  false
what    Lua
source  =input
currentline 2
nparams 0

If, however, I change the code to the following, I can obtain the name of the function passed to pcall:

function test()
    local traceback = debug.traceback();

    print(traceback);
end;

pcall(test);

With the output being as follows:

stack traceback:
    input:2: in function 'test'
    [C]: in function 'pcall'
    input:7: in main chunk
    [C]: in function 'pcall'
    demo.lua:49: in main chunk
    [C]: in ?

How does debug.traceback get this extra information, and using solely Lua is there a way to get it without extracting it from debug.traceback's return value?

2 Answers

debug.getinfo and debug.traceback get their info from various sources, some of them hacky. For instance, the function name is generally extracted from the source code of the calling function: whatever name the code used to look up the thing it called, that's what gets used as the name. (That's why your second code snippet didn't give you the name: pcall doesn't have Lua bytecode backing it up, so it can't tell you "test" unless there's a function in the middle to call it "test".) Lua functions do not have inherent names, any more than Lua integers do; a function is just another kind of value, which can be automatically assigned to a variable via some syntactic sugar.

Functions are values. Values don't have names.

Functions are not "declared" as in some other languages. A function value is created when a function definition is evaluated.

Debugging output is just trying to be helpful in simple cases by giving the name of a variable associated with calling the function value.

Related