🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Debug Info

Debug info is a description of a function. It tells you what kind of function it is and where it was written.

A Lua function and a built-in function differ

Ask for the what field of each function. The answers show two different kinds.

local function greet()
  return "hi"
end
print(debug.getinfo(greet, "S").what)
print(debug.getinfo(print, "S").what)

A Lua function starts on a known line

Ask for the linedefined field of each function. The Lua function starts on line 1.

local function add(a, b)
  return a + b
end
print(debug.getinfo(add, "S").linedefined)
print(debug.getinfo(print, "S").linedefined)

A name is known from inside the call

Ask from inside the function itself. Level 1 means the function making the call.

local function greet()
  local info = debug.getinfo(1, "nS")
  print(info.name)
  print(info.what)
end
greet()

Example

local function double(n)
  return n * 2
end
local info = debug.getinfo(double, "S")
print(info.what)
print(info.linedefined)
print(double(21))

Key points

  • Use debug.getinfo to ask Lua for facts about a function.
  • The what field says Lua for a Lua function and C for a built-in function.
  • The linedefined field gives the line where a Lua function starts.
  • A name comes from the call itself, so ask for it from inside the function.
  • Print single fields, never the whole info table.

In this example, double is defined on line 1 and returns twice its input. The info table says its kind is Lua and its start line is 1. The final print calls double with 21 and shows 42, so the function still works as normal.

Note

A built-in function has a linedefined value of -1.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does debug.getinfo(print, "S").what return?