lua-users home
lua-l archive

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

static int luaB_print (lua_State *L) {
  int n = lua_gettop(L);  /* number of arguments */
  int i;
  lua_getglobal(L, "tostring");
  for (i=1; i<=n; i++) {
    const char *s;
    lua_pushvalue(L, -1);  /* function to be called */
    lua_pushvalue(L, i);   /* value to print */
    lua_call(L, 1, 1);
    s = lua_tostring(L, -1);  /* get result */
    if (s == NULL)
      return luaL_error(L, LUA_QL("tostring") " must return a string to "
    if (i>1) fputs("\t", stdout);
    fputs(s, stdout);
    lua_pop(L, 1);  /* pop result */
  fputs("\n", stdout);
  return 0;

I was looking over Lua's print() to understand what exactly it doctors
in case of more than one argument and I noticed that instead of
lua_pop()'ing the converted string, you could reference the
lua_getglobal(L, "tostring") with just lua_pushvalue(L, nargs + 1);

I'm just not sure if this is a good idea if the stack can't grow on
forever without penalty?  I just thought it might (possibly?) be more
efficient to let those converted strings be popped anyway when we
return from the function.  You can also declare int n as const but I
don't know how much good it would do... I see the fputs() was replaced
with a luai_writestring() in 5.2, so that is a good thing :)

Anyway, it just struck me as a bit odd so I hope the suggestion won't
be taken poorly.