lua-users home
lua-l archive

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


In a function like

static int luaB_getmetatable (lua_State *L) {
  luaL_checkany(L, 1);
  if (!lua_getmetatable(L, 1)) {
    lua_pushnil(L);
    return 1;  /* no metatable */
  }
  luaL_getmetafield(L, 1, "__metatable");
  return 1;  /* returns either __metatable field (if present) or metatable */
}

It could (perhaps perversely) be called with many arguments. So the stack could be value, then lotsofstuff

That's OK, because it gets more stuff off the first value, and then returns it. This uses some stack space. value, lotsofstuff, morestuff

My question is whether it might be better, in cases like this, to set the top of the stack before adding more stuff. So we have just value, then morestuff.

Is that a good idea in cases like this? Or would the extra settop not be worth the effort?

So it would look like:

static int luaB_getmetatable (lua_State *L) {
  luaL_checkany(L, 1);
  lua_settop(L, 1); // ADDED SETTOP
  if (!lua_getmetatable(L, 1)) {
    lua_pushnil(L);
    return 1;  /* no metatable */
  }
  luaL_getmetafield(L, 1, "__metatable");
  return 1;  /* returns either __metatable field (if present) or metatable */
}