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?
Each piece of code that Lua executes, such as a file or a single line in interactive mode, is a chunk. More specifically, a chunk is simply a sequence of statements. A semicolon may optionally follow any statement.
The three dots ( ... ) in the parameter list indicate that the function has a variable number of arguments. When this function is called, all its arguments are collected in a single table, which the function accesses as a hidden parameter named arg .
Lua is not directly interpreted through a Lua file like other languages such as Python. Instead, it uses the Lua interpreter to compile a Lua file to bytecode. The Lua interpreter is written in ANSI C, making it highly portable and capable of running on a multitude of devices.
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!).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With