lua-users home
lua-l archive

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


Hi Tom,

On Tue, Mar 31, 2009 at 7: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!)
>
> Thanks for any help,

The C stack is where you would put local variables.

e.g.

int my_func (lua_State *L)
{
  lua_settop(L, max_arguments_allowed);
  lua_pushinteger(L, 10); /* <-- MAX_LIMIT is at max_arguments_allowed + 1 */
  /* do stuff with that value */
  return 0;
}

If you are "sharing" this value among many C functions, the only
current solution is giving all your C functions an environment where
this data is stored, for example:

/* init code */
lua_newtable(L);
lua_replace(L, LUA_ENVIRONINDEX);
luaL_register(L, ...); /* register all your C functions here to
inherit new environment */
lua_pushinteger(L, 10);
lua_setfield(L, LUA_ENVIRONINDEX, "MAX_LIMIT");
/* ... */

You would then use that environment to access these values.

-- 
-Patrick Donnelly

"One of the lessons of history is that nothing is often a good thing
to do and always a clever thing to say."

-Will Durant