I would like to set different environments on the same function in Lua 5.1 (luajit):
f = function() print(a) end
b = setfenv(f, { a = 1, print = print })
c = setfenv(f, { a = 2, print = print })
I would like b()
and c()
to print different numbers
I've hacked a way by creating new function chunks based on string.dump
and binds env to it, but is there a better more elegant way ? Alternatively, can a function somehow have different upvalues depending on some condition ?
function bind_env(f, env)
return setfenv(loadstring(string.dump(f)), env)
end
Thanks!