[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Redirecting output to non-files?
- From: Rici Lake <lua@...>
- Date: Thu, 1 Dec 2005 19:53:33 -0500
I should have noted that it is not difficult to rewrite io.input and
io.output either.
Here's a quickie sort of solution:
-- Lua 5.1
function io.write(...)
io._output:write(...)
end
-- Lua 5.0
function io.write(...)
io._output:write(unpack(arg))
end
-- This works with either version
function io.output(nameOrFile)
local retval = io._output
if type(nameOrFile) == "string" then
nameOrFile = assert(io.open(nameOrFile, "w"))
end
io._output = nameOrFile
return retval
end
At this point, the only functions you need to write (for the output
case) are io.open and the write method for your object. io.open should,
of course, return one of your objects.
Input is a little more annoying because you have to implement the
various forms of the read patterns: "*a", "*l", "*n", and an integer.
But it's not all that difficult. You can use the code in liolib.c to
guide you if you're doing it in C.
Personally, I hardly ever use io.write or io.output, preferring to use
the idiom:
local f = assert(io.open(filename, "w"))
...
f:write(...)
...
and similarly for reading. I pass open "file" objects as arguments,
rather than relying on the defaults in the io table. This makes it
quite easy to substitute in my own non-file objects, since the client
functions are simply calling the :write and :read methods on the "file"
objects they are being passed.