🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Debug Locals

Debug locals are the variables alive inside a running function. The debug library can read them and change them by position.

Read a running function's parameters

Ask for positions 1 and 2 from inside the function. Each answer gives a name and a value.

local function show(x, y)
  local name, value = debug.getlocal(1, 1)
  print(name)
  print(value)
  local name2, value2 = debug.getlocal(1, 2)
  print(name2)
  print(value2)
end
show(3, 4)

Change a caller's variable

The helper changes position 1 of its caller. The caller then prints the new value twice.

local function inspect()
  debug.setlocal(2, 1, 50)
end
local function price()
  local amount = 20
  inspect()
  print(amount)
  return amount
end
print(price())

Read parameter names from a function value

Pass the function itself instead of a level. Position 3 has no parameter, so it gives nil.

local function add(x, y)
  return x + y
end
print(debug.getlocal(add, 1))
print(debug.getlocal(add, 2))
print(debug.getlocal(add, 3))

Example

local function inspect()
  local name, value = debug.getlocal(2, 1)
  print(name)
  print(value)
  debug.setlocal(2, 1, 50)
end
local function price()
  local amount = 20
  inspect()
  print(amount)
  return amount
end
print(price())
local function add(x, y)
  return x + y
end
print(debug.getlocal(add, 1))

Key points

  • Use debug.getlocal with a level and a position to read a running function's variable.
  • Level 1 means the function making the debug call, and level 2 means the function that called it.
  • The call returns the variable name first and its value second.
  • Use debug.setlocal to change a running function's variable by position.
  • On a function value, the call returns parameter names only, with no values.

In this example, inspect reads the first variable of its caller price and shows the name amount and the value 20. It then sets that variable to 50, so price prints 50 and returns 50. The last line reads the first parameter name of add, which is x.

Note

A position past the last parameter returns nil.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does debug.getlocal(add, 1) return when add is a function value?