lua-users home
lua-l archive

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


Reuben Thomas wrote:
On Sun, 14 Jan 2007 07:27:42 -0000, Mark Edgar <medgar@student.gc.maricopa.edu> wrote:

The ex implementations do this for the io.pipe() function, which returns two Lua file objects.

http://lua-users.org/wiki/ExtensionProposal

     FILE **pf = lua_newuserdata(L, sizeof *pf);
     *pf = 0;
     luaL_getmetatable(L, LUA_FILEHANDLE);
     lua_setmetatable(L, -2);
     *pf = /* your FILE* here */

Thanks, that's great. It looks then as though this is made available without being blessed. Wrapping the above as lua_pushfile is easy; having it blessed and in liolib.c would be nice.

Oops! I neglected to mention that any file userdata you create must have the correct environment table in which the close() method and __gc metamethod will look for a __close function to call. In the ex implementation, only the io.pipe() function creates file userdata, and its environment table is set when it is loaded.

The essential portion of the following section of code copies the environment table from the io.stderr userdatum to the io.pipe() function so that when io.pipe() creates file userdata, these userdata inherit the appropriate environment.

  /* extend the io table */
  lua_getglobal(L, "io");             /* . io */
  if (lua_isnil(L, -1)) return luaL_error(L, "io not loaded");
  copyfields(L, ex_iolib, ex, -1);
  lua_getfield(L, ex, "pipe");        /* . io ex_pipe */
  lua_getfield(L, -2, "stderr");      /* . io ex_pipe io_stderr */
  lua_getfenv(L, -1);                 /* . io ex_pipe io_stderr E */
  lua_setfenv(L, -3);                 /* . io ex_pipe io_stderr */

					-Mark