Re: How do I add a "local" using the c api
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: How do I add a "local" using the c api
- From: Mark Hamburg <mark@...>
- Date: 2009年3月31日 21:35:24 -0700
On Mar 31, 2009, at 8:15 AM, Tom Miles wrote:
Urm, how to put this another way...
When I create a state, I load an associated script file. I want to
add
some variables into the state the script is running in that are only
visible to that script. I can add globals using lua_setglobal(L,
"myvar"), or even lua_setfield(L, LUA_GLOBALSINDEX, "myvar"), but
there
doesn't seem to be an equivelant for locals.
Let me see if I've got the sequence right. You've got C code that
loads a script and executes it to set up the environment. The C code
needs to define some values that only that script should see rather
than having them go into the global environment where they might be
seen by other scripts.
Correct?
It isn't locals that you want because then they would only be visible
to your script and not to the C code.
What you want is a custom environment for the script. So, do something
like the following:
load the script -- you now have a compiled chunk on the top of the
stack
get the environment from the chunk (lua_getfenv) -- call the
environment E for reference in what follows
construct a table T= { } with metatable { __index = E, __newindex = E }
put your special values into T
set T as the environment for the chunk
call the chunk
Now, there will be a set of global values visible only to the script
but all other globals will still be visible and all globals created by
the script will go into the main global environment.
Someone can remind me whether E is the same LUA_GLOBALSINDEX or
LUA_ENVIRONINDEX. I forget which one it is which is why I copped out
and got the environment from the chunk.
Mark