Are there any side-effects to using `arg` as an argument name in Lua?

266 Views Asked by At

I was using arg as an argument name for a function:

function foo(cmd, arg)
    -- etc.
end

I just learned arg is a special, hidden variable that represents a table of arguments when using variable arguments:

function foo(bar, baz, ...)
    -- `arg` now holds arguments 3 and up
end

Should I expect any issues with using arg as an argument name in my code?

2

There are 2 best solutions below

1
On

Firstly, please note that I am using Lua 5.3 and this is the version I prefer. (Though, I imagine I prefer it simply because it is the one I started on and am most familiar with.)

Secondly, what version of Lua are you using? In Lua 5.3, arg refers to the table containing all the command-line arguments passed to a script. For instance, say I had a script called test.lua that looked something like this:

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

If I executed the script as lua test.lua hello there, friend, it would produce the output

hello
there,
friend

Note that in Lua 5.3, arg is a member of the global environment table, _ENV; thus arg is equivalent to _ENV.arg or _ENV["arg"].

In Lua 5.3, it seems that arg as a marker of variadic arguments in a function has been depreciated. A simple, table-based solution exists though, as in the following example:

function foo(...)
    -- Collect the variable arguments in a table.
    local args = {...}
    for i, v in ipairs(args) do print(i, v) end
    return
end

The line local args = {...} has the same behavior of the variable arg within functions in older version of Lua.

0
On

I knew that it would cause problems but wasn't sure of what it was in specific. So I decided to try it myself.

I tried the function displayed on your example, and got a stack overflow error.

And according to the official lua website,

When this function is called, all its arguments are collected in a single table, which the function accesses as a hidden parameter named arg.

So I think it is best to stay away from calling your parameters "arg"