5 ms·
Lua 5.2 has getfenv/setfenv, which lets you view and modify the environment of functions. It even lets you set a metatable on the env, so you can do stuff like
by chc4 10y ago
Lua 5.2 has getfenv/setfenv, which lets you view and modify the environment of functions. It even lets you set a metatable on the env, so you can do stuff like tracing variable gets or sets.
- shakna 10y agoWhat would the Lua equivalent of this be? (let ((a +)) (null-environment)) Edit: I do really want to know if there is a simple answer. Being able to embed Luajit for some things like this would be awesome.
- jpfr 10y agoAssuming f is a function, just do local env = {} env['args'] = {...} setfenv(f, env) return f()
- shakna 10y agoThat is kinda cool, but it does look like a lot of work to bind multiple functions safely into the same environment in any kind of runtime way. Absolutely doable though.
- jpfr 10y agoThat's not difficult at all. You can just say env['f'] = myfunc and the function will be available as f within the environment.
- marktangotango 10y agoCan be a little verbose as this example shows[1], but works really well in practice. [1] http://stackoverflow.com/a/6982080 http://stackoverflow.com/a/6982080
- shakna 10y agoThat does look really interesting, I'll keep it in mind for the future!