lua-users home
lua-l archive

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

On 17-Jun-07, at 2:24 PM, Shane Lee wrote:

Oh, I am most definately on a Linux box :-) I had given some thought
to setting environmental variables when the program begins and then
allowing both the host C program and any lua children to modify the
environs, however I am not sure of the reliability of this. I could
have simply written some functions for the lua lib that create global
buffers accessible from the C program, but I am trying to stay as
portable as possible. Providing custom lua patches for everyone who
want's to run my program is not a very nice thing to think about ;-)

It's entirely reasonable to modify the definition of standard
Lua library functions (base library or otherwise) in a lua_State.
Redefining print(), for example, is quite common. Just insert
the new definition after you load the standard libraries into
the Lua state:

  lua_State *L = lua_open();
  lua_pushcfunction(L, my_print_replacement);
  lua_setglobal(L, "print");

Of course, that only changes print(), not io.write().

print() uses stdin directly, but io.stdin is initialized by
the io. library. So you can (after loading the io. library),
change the definition of io.stdin; it's not strictly necessary
to actually change stdin to do that (and similarly for
io.stdout and io.stderr).

Consequently, you could make use of fopencookie() (on Linux)
or funopen() (on *BSD) in order to create a FILE* which calls
your own C functions, and then set io.stdin and io.stdout (and
optionally io.stderr) to use that FILE*.
None of that requires changing the standard Lua libraries.

Hope that helps.

(fopencookie/funopen have very similar calling protocols. I
don't know why glibc didn't just use the BSD definition.
Unfortunately neither of them are standard C, but they are
widely available on non-windows platforms.)