lua-users home
lua-l archive

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


i didn't actually checked that snipped, and after reading the Dirk's answer i realized that's the right way. sorry for that not tested advice though, in practice i've only used setfenv in Lua 5.1 and not yet used changing environments in Lua 5.2 in real code. (and the load() case i kind of not obvious)


On Sat, Jan 18, 2014 at 7:03 PM, Philipp Janda <siffiejoe@gmx.net> wrote:
Am 18.01.2014 17:45 schröbte Volodymyr Bezobiuk:

Because load() creates own local scope with no upvalues from current local
scope. You can fix this for your case with something like

for i =1,10 do  _ENV = setmetatable({ r = r }, { __index = _ENV })

Doing that will create a long lookup chain ...

Also, changing the `_ENV` upvalue of the running chunk won't change the value `load` uses as the default environment. You would need to modify the globals table stored in the registry for that (or better yet supply a custom environment in the `load` call like Dirk suggested) ...

Philipp




On Sat, Jan 18, 2014 at 6:21 PM, H. van der Meer <H.vanderMeer@uva.nl>wrote:

Collecting function calls for example  r(3,4) in a table I would like to
execute these. But testing reveals I do something wrong.
The program in essence:

local function test(t)
local function r(a,b) return string.format(“a = %d b = %d”, a, b) end
for i =1,10 do
local f = load(t[i])
f()
end
end

This fails with error message:
/usr/local/bin/lua: [string "r(2,364)"]:1: attempt to call global 'r' (a
nil value)
stack traceback:
[string "r(2,364)"]:1: in function 'f'

What is wrong in my code? Why is function r considered global and not
found in the scope of function test(t)?

Thanks in advance
Hans van der Meer