lua-users home
lua-l archive

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


Norman Ramsey wrote:
I am using lua on a POSIX system, and I would like to
find a way to grap the underlying file descriptor associated
with a file, so that I can make it standard output.  E.g.,

local f = assert(io.popen('less', 'w'))
posix.dup2(fileno(f), 0)

My trouble is that I don't know how to implement 'fileno'.
Any suggestions?

If you were trying to change standard output in preparation for running a child process, you can use ex.spawn() from http://lua-users.org/wiki/ExtensionProposal

local i, o = ex.pipe()
ex.spawn{os.getenv"PAGER" or "less", stdin=i}
i:close()
io.output(o)

Or you would use dup2(), fork() and exec() from the posix library.

However, it looks like you simply want print and/or io.write() to write to the pipe instead. In this case:

local f = assert(io.popen('less', 'w'))
io.output(f)

Note that this works for io.write(), but not for io.stdout:write(). It also does not work for print(); you'll have to rewrite it:

function print(...)
	local res = {}
	for i=1,select(#,...) do
		res[#res + 1] = select(i, ...)
	end
	io.write(table.concat(res, "\t"), "\n")
end

					-Mark