lua-users home
lua-l archive

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


On Wed, 8 Nov 2023 at 12:05, Kartik Agaram <ak@akkartik.com> wrote:
> In Lua, "function f() end" is just sugar for "f = function() end". They both produce exactly the same code:

I'm wondering now how debug.traceback computes names of functions. Does it scan bindings from _G (but not locals within functions)?

 Hi Kartik,

try this:

  f = function (a)
      if a == 1 then error("1")
      elseif a == 2 then return 3+g(1)
      else return 4+h(2)
      end
    end
  g = f
  h = f
  f()

you will see this:

  Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
  > f = function (a)
  >>     if a == 1 then error("1")
  >>     elseif a == 2 then return 3+g(1)
  >>     else return 4+h(2)
  >>     end
  >>   end
  > g = f
  > h = f
  > f()
  stdin:2: 1
  stack traceback:
          [C]: in function 'error'
          stdin:2: in function 'g'
          stdin:3: in function 'h'
          stdin:4: in function 'f'
          stdin:1: in main chunk
          [C]: ?
  >

I think that debug.traceback() takes the function names from the
bytecode, that apparently stores how each function - or "method", or
"field" - is called... but I'm not totally sure.

  Cheers,
    Eduardo Ochs
    http://anggtwu.net/luaforth.html