So in Lua, if I want to make a function accept a variable number of arguments, the way I learned to do this was by using ... in the function heading and using the variable "arg" to reference all the arguments in a table. For instance, a completely redundant print function:
function print2(...)
print(unpack(arg))
end
However, within Love it seems that the variable "arg" is by default defined as the location of the main.lua file, even when the ... isn't used anywhere. When I set arg = nil, it remains nil even within a function with the ... . Is there any way to get around this and be able to define a function with a variable number of arguments in Love with ..., or is there an entirely different way to do this by chance?
Functions with a variable number of arguments
Forum rules
Before you make a thread asking for help, read this.
Before you make a thread asking for help, read this.
-
- Prole
- Posts: 2
- Joined: Thu Oct 08, 2015 1:49 am
- slime
- Solid Snayke
- Posts: 3162
- Joined: Mon Aug 23, 2010 6:45 am
- Location: Nova Scotia, Canada
- Contact:
Re: Functions with a variable number of arguments
The implicitly generated "arg" variable is actually a legacy Lua 5.0 feature and was deprecated and removed in Lua 5.1 in 2006 (which is the Lua version that LuaJIT is based on, and love uses LuaJIT.)
Unfortunately the official online version of the Programming in Lua book is still the first edition, which was written before Lua 5.1 was released.
You can just use ... directly, for example:
Unfortunately the official online version of the Programming in Lua book is still the first edition, which was written before Lua 5.1 was released.
You can just use ... directly, for example:
Code: Select all
function print2(...)
-- best, for this situation:
print(...)
-- or:
local args = {...}
print(unpack(args))
-- or, a more robust version of the above because it deals with nils properly, just like the first example:
local nargs = select("#", ...)
local args = {}
for i = 1, nargs do
args[i] = tostring((select(i, ...)))
end
print(table.concat(args, "\t"))
end
-
- Prole
- Posts: 2
- Joined: Thu Oct 08, 2015 1:49 am
Re: Functions with a variable number of arguments
Oh, okay, thanks! For some reason the "arg" variable still works for me in regular Lua, though, even though I believe the Lua for windows version I have is 5.1.4.
- slime
- Solid Snayke
- Posts: 3162
- Joined: Mon Aug 23, 2010 6:45 am
- Location: Nova Scotia, Canada
- Contact:
Re: Functions with a variable number of arguments
Lua 5.1 can be built with 'Lua 5.0 compatibility mode' enabled, which prevents the deprecated functions from being removed. I think many prebuilt binaries of standalone Lua 5.1 are built like that, but LuaJIT has no such build option.
Who is online
Users browsing this forum: Bing [Bot], Google [Bot] and 2 guests