lua-users home
lua-l archive

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


On Fri, 2009-12-11 at 21:26 +0100, Gert wrote: 
> Hello,
> 
> Is there a way for dynamically loaded code to access local variables within a
> function ? What I'm trying to do basically looks like this:

I have tried to achieve the same thing, and basically ended up
collectiong all the locals and upvalues using functions from debug
table, and using setfenv() on the loaded code. The locals table has a
metatable with __index pointing to the environment of calling functions,
so it also has access to "globals".

Here is a proof of concept:

function eval(str)
  local f = loadstring('return ' .. str)
  if f then
    local locals = {}
    local caller = debug.getinfo(2, 'f').func
    local i, k, v = 2, debug.getupvalue(caller, 1)
    while k do
      locals[k] = v
      i, k, v = i+1, debug.getupvalue(caller, i)
    end
    i, k, v = 2, debug.getlocal(2, 1)
    while k do
      locals[k] = v
      i, k, v = i+1, debug.getlocal(2, i)
    end
    local fenv = debug.getfenv(caller)
    setmetatable(locals, { __index = fenv })
    setfenv(f, locals)
    return f()
  end
end

X = 22

function dummy(x)
  local x = 1
  do
    local x = 2
    local y =  x * x
    x = x + 1
    if x > 0 then
      local x = 33
      print(eval 'x * y + X')
    end
  end
end

dummy(10)

> 154

I am not sure whether it handles all cases correctly, but for simple
purposes it should be enough.