Lua "arg" variable not working (SOLVED)

Lua has a global variable arg available for variable arguments in functions. For some reason it is set to nil?

Here is a clean example for how the expected behavior is.

We use LuaJIT for all platforms but iOS 64 and HTML5. The LuaJIT FAQ reads:

“Q: Why do I get this error: “attempt to index global ‘arg’ (a nil value)”?
Q: My vararg functions fail after switching to LuaJIT!
LuaJIT is compatible to the Lua 5.1 language standard. It doesn’t support the implicit arg parameter for old-style vararg functions from Lua 5.0.
Please convert your code to the Lua 5.1 vararg syntax.”

You can get the arguments in two ways:

function foo(...)
   local args = {...}
   print(args[1])
   print(select(1, ...))
end
2 Likes

I might be missing something, but I cannot seem to use argin my local Lua 5.2. Do I need to set things up first?

Lua 5.2.4  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> function test(...)
>> print("num args", #arg)
>> end
> test("hello")
stdin:2: attempt to get length of global 'arg' (a nil value)
stack traceback:
	stdin:2: in function 'test'
	stdin:1: in main chunk
	[C]: in ?

It’s probably removed in 5.2 and exists for backwards compatibility in 5.1

1 Like

That explains everything. Thanks @britzl!