lua-users home
lua-l archive

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


It was thus said that the Great Kenk once stated:
> Dang, these table things are confusing me. I get how to pass a single table 
> back to lua. How do I pass a table structure back that has nested tables in 
> it? So for example, I call a C method from Lua script which has a table 
> type as a return value that looks something like (and could have multiple 
> nested tables etc. But I'm guessing once I understand how to do one nested, 
> it becomes a repeat):
> 
> { {name="Scooby",age=45, 
> type="Dog",someusertype=<userdata>},{name="Shaggy",age=24, 
> type="Human",someusertype=<userdata>}}
> 
> (Obviously the example setup is built from some values in C and so on);
> 
> Thanks for the help!

  What follows is a function I wrote (as an exercise to learn the Lua API)
that returns a table structured as:

{
  cwd      = "/home/spc/source/lua/C" ,
  pid      = 864 ,       
  loadave  = { 0.00, 0.00, 0.00 }
}

It also sets a metatable on the loadave table to pretty print the results,
and to make it read-only.  The functions defined are left as an exercise for
the reader.

  -spc (Hope this helps some ... )

static int info(lua_State *L)
{
  lua_newtable(L);
 
  lua_pushliteral(L,"pid");
  lua_pushnumber(L,getpid());
  lua_settable(L,-3);
 
  char buffer[FILENAME_MAX];	/* valid C99 syntax here */
  
  getcwd(buffer,FILENAME_MAX);
  lua_pushliteral(L,"cwd");
  lua_pushlstring(L,buffer,strlen(buffer));
  lua_settable(L,-3);
  
  double load[3];	/* and C99 here as well */
  
  if (getloadavg(load,3) != -1)
  { 
    /*----------------------------------------------
    ; equiv of
    ;   loadave = {} 
    ;   loadave[1] = x;
    ;   loadave[2] = y;
    ;   loadave[3] = z;
    ;----------------------------------------------*/
 
    lua_pushliteral(L,"loadave");
    lua_createtable(L,3,0);
 
    lua_pushnumber(L,1);
    lua_pushnumber(L,load[0]);
    lua_settable(L,-3);
 
    lua_pushnumber(L,2);
    lua_pushnumber(L,load[1]);
    lua_settable(L,-3);
 
    lua_pushnumber(L,3);
    lua_pushnumber(L,load[2]);
    lua_settable(L,-3);
 
    /*---------------------------------------------
    ; mt = {}
    ; mt.__tostring = silly_loadave__toprint
    ; mt.__newindex = silly_loadave__newindex
    ; setmetable(loadave,mt);
    ;---------------------------------------------*/
 
    lua_createtable(L,0,2);
    lua_pushliteral(L,"__tostring");
    lua_pushcfunction(L,silly_loadave__toprint);
    lua_settable(L,-3);
 
    lua_pushliteral(L,"__newindex");
    lua_pushcfunction(L,silly_loadave__newindex);
    lua_settable(L,-3);
 
    lua_setmetatable(L,-2);
 
    lua_settable(L,-3);
  }
  
  return 1;
}