[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: How to change _ENV's value in a pure C function?
- From: Patrick Rapin <toupie300@...>
- Date: Sat, 24 Dec 2011 09:35:21 +0100
>> lua_pushcfunction(L, myfunc);
>> luaL_loadstring(L, "local _ENV,func = ... return func()");
>> lua_call(L, 2, 0);
Have you tried your code ? I don't think so.
First, you have to push the function onto the stack *before* the
arguments (line 3 should be the first one).
And second, this construct won't change the environment of "myfunc".
It only changes the environment of the little chunk.
Remember, _ENV is handled as an *upvalue*. Once compiled, "myfunc"
does not look up for an external _ENV variable, but has a direct
reference to it.
The only way to change the environment of such a function is
enumerating its upvalues through the debug API to find _ENV (ugly!)
> I'm not totally sure what you want to do ...
> To load a Lua source string with a different _ENV, you just use the
> Lua function "load" ("luaB_load" in C), since "load" replaced
> loadstring in 5.2 ... e.g. "load (MYSTRING, nil, nil, MYENV)".
Like Miles, I think you want to use "load" function from Lua.
>From C, use luaL_loadbufferx or similar function to compile, and then
change the first upvalue of the chunk using lua_setupvalue.