Functions with a variable number of arguments

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
radioactive116
Prole
Posts: 2
Joined: Thu Oct 08, 2015 1:49 am

Functions with a variable number of arguments

Post by radioactive116 »

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?
User avatar
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

Post by slime »

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:

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
radioactive116
Prole
Posts: 2
Joined: Thu Oct 08, 2015 1:49 am

Re: Functions with a variable number of arguments

Post by radioactive116 »

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.
User avatar
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

Post by slime »

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.
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot], Google [Bot] and 3 guests