lua-users home
lua-l archive

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


> -----Original Message-----
> From: lua-bounces@bazar2.conectiva.com.br [mailto:lua-
> bounces@bazar2.conectiva.com.br] On Behalf Of Mark Hamburg
> Sent: 01 April 2009 05:35
> To: Lua list
> Subject: Re: How do I add a "local" using the c api
> 
> 
> 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?

Yes that is correct, only I don't need the "locals" to be visible to the
c code after I've added them to the state.

> 
> 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
> 

I think you may be on to something here, although it needs slight
modification as I already set the states environment to a parent state
so they can share globals, although the more I think about it, the more
I wonder why I decided to that in the first place.  

I'm getting a little confused here again as well, if another state were
to call getglobal() on our first state, would it be able to see it using
this methood?