Shell Access

lua-users home
wiki

The following examples relate to allowing Lua to interact with the shell, such as for shell scripting.

[!] VersionNotice: The below code pertains to an older Lua version, Lua 4. Some of it does not run as is under Lua 5.

Piping from command

This reads output from a process via a pipe. There is a way to make this work on Windows too (see PipesOnWindows, not needed for Lua 5.1.2, see below).

-- Perform a shell command and return its output
--   c: command
-- returns
--   o: output
function shell(c)
  local input = _INPUT
  local o, h
  h = readfrom("|" .. c)
  o = read("*a")
  closefile(h)
  _INPUT = input
  return o
end

On lua5.0.2 I think it should be something like:

function shell(c)
  local o, h
  h = assert(io.popen(c,"r"))
  o = h:read("*all")
  h:close()
  return o
end

Lua 5.1.2: io.popen runs fine under Windows XP "out-of-the-box", even from within a non-DOS application --AndreasRozek

Process files in command-line arguments

A typical thing to want to do in a command-line utility is to process each file given on the command line. Here's a function to encapsulate this process:

-- Process all the files specified on the command-line with function f
--   name: the name of the file being read
--   i: the number of the argument
function processFiles(f)
  for i = 1, getn(arg) do
    if arg[i] == "-" then readfrom()
    else readfrom(arg[i])
    end
    file = arg[i]
    f(arg[i], i)
    readfrom() -- close file, if not already closed
  end
end

RecentChanges · preferences
edit · history
Last edited April 17, 2007 5:26 pm GMT (diff)