A recent (Jan 2006) discussion on the mailing list has prompted me to attempt to design an extended API which extends the Lua API by adding functions to the os and io namespaces.

This is not a proposal to modify the Lua core, but a design proposal for an API which extends the Lua core. This API is meant to provide a more complete programming environment for stand-alone Lua programs on today's popular operating systems (Windows, MacOSX and POSIX platforms).

There are [implementations for POSIX and Windows] hosted on LuaForge. These are highly usable implementations, but should be considered only for testing purposes while the API is still being standardized.

ex API

Note that all these functions return the standard (nil,"error message") on failure and that, unless otherwise specified, they return (true) on success.

Initialization

require "ex"
marks a Lua program which uses this API

Environment

os.getenv(name)
get an environment value

os.setenv(name, value)
set/modify an environment value

os.setenv(name, nil)
remove an environment value

os.environ()
returns a copy of the environment (a simple Lua table)

File system (mostly borrowing from LuaFilesystem?)

os.chdir(pathname)
change working directory

os.mkdir(pathname)
create a directory

os.remove(pathname)
remove a file or directory

pathname = os.currentdir()
get working directory path

for entry in os.dir(pathname) do ; end
iterates over the entries in a directory. The pathname argument is optional; if missing the current directory is used.
Special directory entries such as "." and ".." are not returned.

entry = os.dirent(pathname)
entry = os.dirent(file)
gets information about a directory entry via pathname or open file

Both the iterator function returned by os.dir() and the os.dirent() function return an 'entry' table. This table contains at least the following fields:

entry.name= the filename (Note that os.dirent() does need to set this field)
entry.type= "file" or "directory" (or an implementation-defined string)
entry.size= the file size in bytes

Implementations may add other fields or even methods.

I/O (locking and pipes)

file:lock(mode, offset, length)
io.lock(file, mode, offset, length)
lock or unlock a file or a portion of a file; 'mode' is either "r" or "w" or "u"; 'offset' and 'length' are optional
A mode of "r" requests a read lock, "w" requests a write lock, and "u" releases the lock. Note that the locks may be either advisory or mandatory.

file:unlock(offset, length)
io.unlock(file, offset, length)
equivalent to file:lock("u", offset, length) or io.lock(file, "u", offset, length)

Note that both file:lock() and file:unlock() extend the metatable for Lua file objects.

rd, wr = io.pipe()
create a pipe; 'rd' and 'wr' are Lua file objects

Process control

os.sleep(seconds)
os.sleep(interval, unit)
suspends program execution for interval/unit seconds; 'unit' defaults to 1 and either argument can be floating point. The particular sub-second precision is implementation-defined.
os.sleep(3.8) -- sleep for 3.8 seconds
local microseconds = 1e6
os.sleep(3800000, microseconds) -- sleep for 3800000 µs
local ticks = 100
os.sleep(380, ticks) -- sleep for 380 ticks

proc = os.spawn(filename)
proc = os.spawn{filename, [args-opts]}
proc = os.spawn{command=filename, [args-opts]} 
create a child process

'filename' names a program. If the (implementation-defined) pathname is not absolute, the program is found through an implementation-defined search method (the PATH environment variable on most systems).

If specified, [args-opts] is one or more of the following keys:

[1]..[n]= the command line arguments

args= an array of command line arguments

env= a table of environment variables

stdin= stdout= stderr= io.file objects for standard input, output, and error respectively

It is an error if both integer keys and an 'args' key are specified.

An implementation may provide special behavior if a zeroth argument (options.args[0] or options[0]) is provided.

The returned 'proc' userdatum has the following method:

exitcode = proc:wait()
wait for child process termination; 'exitcode' is the code returned by the child process

Summary

All functions are also available under the ex namespace:

ex.getenv(name)
ex.setenv(name, value)
ex.environ()
ex.chdir(pathname)
ex.mkdir(pathname)
ex.currentdir()
ex.dir(pathname)
ex.dirent(pathname)
ex.lock(file, mode, offset, length)
ex.unlock(file, offset, length)
ex.pipe()
ex.sleep(interval, [unit])
ex.spawn(...)
ex.wait(proc)

Note that ex.getenv is here mostly for parallelism, but also because under Windows, using the SetEnvironmentVariable?() API requires overriding the standard os.getenv implementation which uses getenv() to use GetEnvironmentVariable?() instead.

Examples

require "ex"

-- run the echo command
proc = os.spawn"/bin/echo"
proc = os.spawn{"/bin/echo", "hello", "world"}
proc = os.spawn{command="/bin/echo", "hello", "world"}

-- run the id command
vars = { LANG="fr_FR" }
proc = os.spawn{"/bin/id", "-un", env=vars}
proc = os.spawn{command="/bin/id", "-un", env=vars)

-- Useless use of cat
local rd, wr = assert(io.pipe())
local proc = assert(os.spawn("/bin/cat", {stdin=rd}))
rd:close()
wr:write("Hello world\n")
wr:close()
proc:wait()

-- Run a program with a modified environment
local env = os.environ()
env.LUA_PATH = "/usr/share/lib/lua/?.lua"
env.LUA_CPATH = "/usr/share/lib/lua/?.so"
local proc = assert(os.spawn("lua", {args = {"-e", 'print"Hello world\n"'}, env=env }))
proc:wait()

-- popen2()
function popen2(...)
  local in_rd, in_wr = io.pipe()
  local out_rd, out_wr = io.pipe()
  local proc, err = os.spawn{stdin = in_rd, stdout = out_wr, ...}
  in_rd:close(); out_wr:close()
  if not proc then
    in_wr:close(); out_rd:close()
    return proc, err
  end
  return proc, out_rd, in_wr
end
-- usage:
local p, i, o = assert(popen2("wc", "-w"))
o:write("Hello world"); o:close()
print(i:read"*l"); i:close()
p:wait()