2
votes

In the Lua command line, when I pass arguments to a script like this:

lua myscript.lua a b c d

I can read the name of my script and arguments from the global arg table. arg[0] contains the script name, arg[1] - arg[#arg] contain the remaining arguments. What's odd about this is table is that it has a value at index 0, unlike every other Lua array which starts indexing at 1. This means that when iterating over it like this:

for i,v in ipairs(arg) do print(i, v) end

the output only considers index 1-4, and does not print the script name. Also #arg evaluates to 4, not 5.

Is there any good reason for this decision? It initially took me aback, and I had to verify that the manual wasn't mistaken.

2
One could argue that the script name is not an argument to the script.Tom Blodget
"Lua array which starts indexing at 1": Array is not a Lua domain concept. Every Lua table sequence starts indexing at 1.Tom Blodget

2 Answers

3
votes

Asking why certain design decisions were made is always tricky because only the creator of the language can really answer. I guess it was chosen such that you can iterate over the arguments using ipairs and don't have to handle the first one special because it's the script name and not an argument.

#arg is meaningless anyway because it counts only the number of elements in the consecutive array section but the zeroth and negative indices are stored in the hashmap section. To obtain the actual number of elements use

local n = 0
for _ in pairs(arg) do
    n = n + 1
end

At least it is documented in Programming in Lua:

A main script can retrieve its arguments in the global variable arg. In a call like

prompt> lua script a b c

lua creates the table arg with all the command-line arguments, before running the script. The script name goes into index 0; its first argument (a in the example), goes to index 1, and so on. Eventual options go to negative indices, as they appear before the script. For instance, in the call

prompt> lua -e "sin=math.sin" script a b

lua collects the arguments as follows:

arg[-3] = "lua"
arg[-2] = "-e"
arg[-1] = "sin=math.sin"
arg[0] = "script"
arg[1] = "a"
arg[2] = "b"

More often than not, the script only uses the positive indices (arg[1] and arg[2], in the example).

2
votes

arg in Lua mimics argv in C: arg[0] contains the name of the script just like argv[0] contains the name of the program.

This does not contradict 1-based arrays in Lua, since the arguments to the script are the more important data. The name of the script is seldom used.