lua-users home
lua-l archive

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


Gang,


To support rerouting of lua's output into one or more of our app's views, I
added a field to lua's global_State: a c function ptr, which I stuff on
open:

    itsLuaState = lua_open();
    itsLuaState->l_G->outputHandler = &HandleLuaOutput;


typedef void (*lua_output_handler)(char *output);

typedef struct global_State {
  stringtable strt;  /* hash table for strings */
  GCObject *rootgc;  /* list of (almost) all collectable objects */
  GCObject *rootudata;   /* (separated) list of all userdata */
  GCObject *tmudata;  /* list of userdata to be GC */
  Mbuffer buff;  /* temporary buffer for string concatentation */
  lu_mem GCthreshold;
  lu_mem nblocks;  /* number of `bytes' currently allocated */
  lua_CFunction panic;  /* to be called in unprotected errors */
  TObject _registry;
  TObject _defaultmeta;
  struct lua_State *mainthread;
  Node dummynode[1];
  TString *tmname[TM_N];
  lua_output_handler outputHandler;       // <------- new field
} global_State;



And I then modified luaB_print to instead of going to through fputs, etc, it
simply calls my handler:



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, "`tostring' must return a string to
`print'");
          if (i>1)
              (*(L->l_G->outputHandler))("");
        (*(L->l_G->outputHandler))((CStringPtr)s);
        lua_pop(L, 1);  /* pop result */
    }
     (*(L->l_G->outputHandler))((CStringPtr)"\n");

  return 0;
}

This has been working fine, but I thought I'd double check and see if I'm
making any assumptions or am not aware of anything I should be in regards to
such a change.

So, sound ok to do this?

Thx,
Ando