Birk
Birk

Reputation: 211

Lua: how to use debug.getlocal

local function ThisIsAFunction()
    local test1 = "im a local var"
    local asd = "im also a local var"
end

How would I use debug.getlocal to get the value of the local functions inside "ThisIsAFunction"

Upvotes: 3

Views: 2557

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

Something like this should work:

local function printLocals()
  local i = 1
  while true do
    local name, value = debug.getlocal(2, i)
    if not name then break end
    print(name, i, value)
    i = i + 1
  end
end

local function ThisIsAFunction()
  local test1 = "im a local var"
  local asd = "im also a local var"
  printLocals()
end

ThisIsAFunction()

This should print:

test1   1   im a local var
asd 2   im also a local var

Note that getlocal can only get values for the function/frame that is already on the stack (that's why you need to call printLocals from the function you want to inspect).

You can use getinfo to inspect the function (from outside), but you need to be executing the function to inspect, so you need to make an explicit call to printLocals or use a debug hook to do an implicit one.

Upvotes: 3

Related Questions