lua-users home
lua-l archive

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


On Tue, Mar 31, 2009 at 6:22 AM, Tom Miles <Tom@creative-assembly.co.uk> wrote:
> Hi,
>
> I don't know if this has been discussed before, I had a quick look at
> the list archives, but only found something a bit relevant that didn't
> seem to amount to anything.
>
> My question is this though.  I have several states that inherit their
> environment from parent states.  When I initiate a state I call some c
> code to add some extra standard bits and pieces, some of which I want
> child states to inherit, others I don't.  In a script I would declare
> these as local, but I haven't found anything that copies the required
> behaviour in the c api.  I've found lua_setlocal(), but that's part of
> the debug library, so would seem inappropriate, and the only reference I
> found on the list before mentions upvalues.  Are local variables just
> upvalues for the entire state or something?
>
> In short, how do I achieve something like this from the c api when I
> create my state?
>
> -- script start
> local MAX_LIMIT = 10
>
> -- lots of functions that use MAX_LIMIT everywhere
>
> -- end script
>
> (Short script huh!)

One way is with a c closure and upvalues:

http://www.lua.org/manual/5.1/manual.html#lua_pushcclosure
http://www.lua.org/manual/5.1/manual.html#lua_getupvalue

That's probably closest to your lua code.

Another would be with a function environment:

http://www.lua.org/manual/5.1/manual.html#lua_setfenv

Sam