lua-users home
lua-l archive

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

Hello I have some newbie questions in the Programming in Lua Book (2nd ed).

In Chapter 28 where a custom array type is made with userdata and metatables, why isn't the stack 'balanced' in the luaopen_array? I thought the stack should always balance back to what you started with at the beginning of the function. In the 1st metatable example the stack is 1 larger than when it started. In the object example, the stack is 2 larger than when it started. (The function still returns 1.  What does the return value mean?)

If I needed a second kind of array (or maybe a struct just to be a little different) in this same library, which needed its own metatable, is it safe to just creating new different metatables in the luaopen_ function? So does this work and safe?

int luaopen_array (lua_State *L) {

  luaL_newmetatable(L, "LuaBook.array");

  lua_pushvalue(L, -1);
  lua_setfield(L, -2, "__index");
  luaL_register(L, NULL, arraylib_m_forarray);

  luaL_newmetatable(L, "LuaBook.struct");

  lua_pushvalue(L, -1);
  lua_setfield(L, -2, "__index");
  luaL_register(L, NULL, arraylib_m_forstruct);

  luaL_register(L, "array", arraylib_f);
  return 1;

I saw this in the 5.1 ref manual:

"The luaopen_* functions (to open libraries) cannot be called directly, like a regular C function. They must be called through Lua, like a Lua function."

Why is this and how should I be opening this library from C?

And must all my library open methods be named luaopen_*? Do things break if I call it something else like init_mylib()?

Thank you