lua-users home
lua-l archive

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


I came across this issue while investigating a bug in my debugger (MobDebug).

It looks like debug.setlocal does not correctly restore variables that
are localized inside subblocks in a function.

When I run the following code:

local a = 1
do
  local a = 2
  print('local a = 2', a)
end
print('local a = 1', a)

I expect it to print

local a = 2	2
local a = 1	1

and it indeed does this. But when I add a debug hook that saves and
restores variables, the variable values is not properly restored and
it prints:

local a = 2	2
local a = 1	2

I want to be able to store and restore local variables properly at any
point in the program. Am I doing it wrong, or is it a bug (or maybe a
limitation of the current debug interface)? If it's not me doing it
wrong, is there a workaround to do it right?

The full script is included below (I'm running Lua 5.1.4). Thank you. Paul.

local function capture_vars()
  local vars = {}
  local func = debug.getinfo(3, "f").func
  local i = 1
  while true do
    local name, value = debug.getlocal(3, i)
    if not name then break end
    if string.sub(name, 1, 1) ~= '(' then vars[name] = value end
    i = i + 1
  end
  return vars
end

local function restore_vars(vars)
  if type(vars) ~= 'table' then return end
  local func = debug.getinfo(3, "f").func
  local i = 1
  local written_vars = {}
  while true do
    local name = debug.getlocal(3, i)
    if not name then break end
    if string.sub(name, 1, 1) ~= '(' then debug.setlocal(3, i, vars[name]) end
    written_vars[name] = true
    i = i + 1
  end
end

local function debug_hook(event, line)
  restore_vars(capture_vars())
end

debug.sethook(debug_hook, "l")
local a = 1
do
  local a = 2
  print('local a = 2', a)
end
print('local a = 1', a)