interactive lua: command line arguments

71,351

Solution 1

You're missing the arg vector, which has the elements you want in arg[1], arg[2], and so on:

% lua -i -- /dev/null one two three
Lua 5.1.3  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> print(arg[2])
two
> 

More info in the Lua manual section on Lua standalone (thanks Miles!).

Solution 2

In addition to the arg table, ... contains the arguments (arg[1] and up) used to invoke the script.

% lua -i -- /dev/null one two three
Lua 5.1.3  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> print(...)
one     two     three

Solution 3

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...

Solution 4

If you run file.lua in cmd of freeswitch

freeswitch> luarun prog.lua arg1

You can use prog.lua:

#print(argv[1])

And run: $lua prog.lua arg1 (run in script folder) You can use prong.lua:

#print(arg[1])
Share:
71,351
mr calendar
Author by

mr calendar

please delete me

Updated on December 28, 2020

Comments

  • mr calendar
    mr calendar over 3 years

    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?

  • mr calendar
    mr calendar almost 14 years
    You're absolutely right, I am! Whereabouts in the manual is that? I'm not finding my way round it very well ATM. Cheers
  • cxw
    cxw over 6 years
    Thank you for the answer! I tried lua -i -- one two three on lua 5.2.4 and got cannot open one: No such file or directory. That makes me think the /dev/null is required (per [script [args]] in the manual, not [script] [args]) --- am I understanding correctly? If you don't object, I will update the answer to explain. Much appreciated!
  • Idodo
    Idodo over 5 years
    How would one define their own table name instead of "arg"?
  • Jesse Chisholm
    Jesse Chisholm almost 5 years
    @cxw re: /dev/null is required You could put any lua script path there. /dev/null just means there is no script to run before entering interactive mode.