Loaded library on stack

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Loaded library on stack

King, Mike

I’m new to Lua.  I’m in the process of embedding Lua within an application I wrote.  The only question I have at the moment is when I load a library the table is left on the stack, is it okay to pop it off?  All the example code I’ve seen never do this.  Isn’t the stack space limited?

 

luaopen_base(L);             /* opens the basic library */

luaopen_table(L);            /* opens the table library */

luaopen_io(L);               /* opens the I/O library */

luaopen_string(L);           /* opens the string lib. */

luaopen_math(L);             /* opens the math lib. */

Reply | Threaded
Open this post in threaded view
|

Re: Loaded library on stack

Doug Rogers-4
King, Mike wrote:

> The only question I have at the moment is when I
> load a library the table is left on the stack, is it okay to pop it off?

The table is typically returned on the stack so that it may be named by
the caller.

In the case of the standard libraries (base, table, etc.), the names are
hard coded using luaL_register(), but they still follow the convention
of leaving the table on the stack to be used by the caller if needed.
The use of 5 stack slots is not a big deal during the luaopen_XXX()
calls for the standard libraries.

For my own (5.0) code I use the code below, where 'lib' is a C array of
open/name pairs. It allows me to mix and match the new method with the
old (back when the library tables were NOT left on the stack).

  for (; lib->open != NULL; lib++)
  {
    /*
     * If there's no name, just run the opener. Otherwise, push the
     * name, check that there's something on the stack, then put it
     * in the global table.
     */
    lib->open(L);

    if ((lib->name[0] != 0) &&
        (lua_gettop(L) > 0))
    {
      lua_pushstring(L, lib->name);
      lua_insert(L, -2);            /* Put string behind table. */
      lua_rawset(L, LUA_GLOBALSINDEX);
    }

    lua_settop(L, 0);
  }

I believe 5.1 has better facilities for this.

Hope that helps,

Doug

--
--__-__-____------_--_-_-_-___-___-____-_--_-___--____
Doug Rogers - ICI - V:703.893.2007x220 www.innocon.com
-_-_--_------____-_-_-___-_--___-_-___-_-_---_--_-__-_