38

Does Lua support something like C's __LINE__ macro, which returns the number of the current code line? I know Lua has a special built-in variable called _G, but I don't see line number in there...

prideout
  • 2,895
  • 1
  • 23
  • 25

1 Answers1

54

From Lua using debug.getinfo, e.g.,

local line = debug.getinfo(1).currentline

From C using lua_getinfo (This will return the linenumber inside lua code)

  lua_Debug ar;
  lua_getstack(L, 1, &ar);
  lua_getinfo(L, "nSl", &ar);
  int line = ar.currentline   

http://www.lua.org/manual/5.1/manual.html#lua_getinfo

http://www.lua.org/manual/5.1/manual.html#pdf-debug.getinfo

May Oakes
  • 4,359
  • 5
  • 44
  • 51
Tuomas Pelkonen
  • 7,783
  • 2
  • 31
  • 32
  • Would the above work like this?: io.write("Error on line" .. line) – qroberts Mar 01 '13 at 14:04
  • 3
    Does this work on Lua 5.3. I was getting access violation errors in Windows. Also does work for cases when executing script as a file and in a variable (dofile and doscript calls)? – TrustyCoder Mar 04 '17 at 15:13
  • 2
    @TrustyCoder I had same problem. This only works inside a C implementation of a lua function. It does NOT work after a pcall trying to see what went wrong, I got exceptions too. (So I made my function error-handlers include this info in their error string). – david van brink Jul 12 '17 at 20:11