lua-users home
lua-l archive

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

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(...)

-- Lua 5.0
function io.write(...)

-- This works with either version
function io.output(nameOrFile)
  local retval = io._output
  if type(nameOrFile) == "string" then
    nameOrFile = assert(, "w"))
  io._output = nameOrFile
  return retval

At this point, the only functions you need to write (for the output case) are and the write method for your object. 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(, "w"))

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.