lua-users home
lua-l archive

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


Thanks to those who reacted on the posting of the question below. They helped me to track down the misunderstanding in my original code. For the record I give the solution that worked for me in a mixture of code and pseudo code. It might be of use for someone. Ultimately it came to not registering in the module's metatable but in the table itself (why are the right answers always so simple in retrospect? ;-)

This is from the main luaopen_xxx function:

 lua_newtable(L); /* table for C-function environment */
 lua_replace(L, LUA_ENVIRONINDEX); /* set it */
 luaL_newmetatable(L, IO_FILEHANDLE); /* filehandle ident metatable */
 lua_pushvalue(L, -1); /* link to self for oo access fp:func() */
 lua_setfield(L, -2, "__index"); /* set index field */
 <etc>
 /* Register the API functions for object oriented access to filehandle. */
 luaL_register(L, NULL, io_register); /* filehandle functions */
 /* Register the module callable functions. */
 luaL_register(L, MODULENAME, io_register); /* ioio table carries api */
 /* Create filehandles for the standard files stderr, stdin, stdout. */
 io_standardfilecreate(L, IO_STDERR, stderr, "w"); /* leaves file object on stack top */
 lua_setfield(L, -2, "stderr"); /* make 'stderr' known */
 <etc>
 return 1; /* return value is the ioio table */


On 31 dec 2010, at 21:17, Hans van der Meer wrote:

> In Lua I can write
>   io.stderr:write(msg)
> and get the msg on the stderr output stream.
> Therefore I conclude io.stderr is in the globally accessible space.
> 
> In an alternative, special output module I want to duplicate this behaviour. Although I have managed to get working:
>    io.write(stderr, msg)
> The equivalent of the above io.stderr:write(msg) does not know stderr: "attempt to index field 'stderr' (a nil value)"
> 
> I have in earnest sought in the documentations as well as in the sources, but could not find how to accomplish this. Is there someone who will enlighten me and point in the right direction?
> 
> Thanks in advance,
> Hans van der Meer
> 
>