I wish to do
lua prog.lua arg1 arg2
from the command line
Inside prog.lua, I want to say, for instance
print (arg1, arg2, '\n')
Lua doesn't seem to have argv[1] etc and the methods I've seen for dealing with command line arguments seem to be immature and / or cumbersome. Am I missing something?
If you run file.lua in cmd of freeswitch
You can use prog.lua:
And run:
$lua prog.lua arg1
(run in script folder) You can use prong.lua:Lua stores arguments in a table. This table is the "arg" table. You can access the passed arguments inside using arg[1], arg[2], ...
arg[0] is the name of the lua program. arg[1] is the first argument passed, arg[2] is the second argument passed and so on...
For OP and future visitors,
The library of Lua doesn't contain
injecting a table 'args' into globals from command line switches
. The program built fromlua.c
does, however, it is near impossible to use. The reason it is impossible to use is that program does NOT like multiple switches.This is one of the reasons why my REPL/code executor
LuaConsole
was built. It gives you the tableargs
as well as sends a tuple to the root pcall function (your executing environment is really a top-level pcall with probably an error handler attached). So bothargs[n]
andlocal a = {...}; a[n] ...;
all work properly with as many switches as you want. For example, -e to execute code from cmd line, -l to specify libraries, etc. It supports anything lua51 and up.If you are having troubles with the program in the library, I highly suggest you check out https://www.github.com/tilkinsc/LuaConsole as it will save you the headache of dealing with a broken-feeling program. There are also other alternatives out there such as for web, fengari.
Hope this helps you!
In addition to the
arg
table,...
contains the arguments (arg[1] and up) used to invoke the script.You're missing the
arg
vector, which has the elements you want inarg[1]
,arg[2]
, and so on:More info in the Lua manual section on Lua standalone (thanks Miles!).