How do I access command-line arguments?
The command-line arguments are passed to a script in the global table arg
. The actual arguments are arg[i]
where i
runs from 1
to #arg
- or you could use ipairs
. arg[0]
is the name of the script, as it was called; arg[-1]
is the name of the Lua executable used.
> lua arg.lua one "two three"
1 one
2 two three
-1 lua
0 arg.lua
(where 'arg.lua' is just 'for k,v in pairs(arg) do print(k,v) end`)
You can use arg[0]
to find out where your script is installed; if it's an absolute path, then use that, otherwise use the current directory plus the path given.
It is possible to make a directly executable script under Unix by making the first line '#!/usr/local/bin/lua' or '#!/usr/bin/env lua' and making the script itself executable. On Windows you can achieve this by adding ';.lua' to the PATHEXT environment variable and make execution the default action when opening Lua files.
Note that arg
is set by the standard interpreter; if your C/C++ program launches a script with luaL_dofile
then arg
will be nil
, unless you specifically set it.