Search code examples
lua

How to handle variable number of arguments


I've understood that arg is deprecated and is no longer supported in later versions of Lua. I have a lot of functions written in Lua 5.1 that have variable number of arguments and I am moving to Lua 5.4 but I have no idea how to handle them without arg.

-- Without arg, nil entries are ignored.
local function printMyArgumentsA( ... )
    local t = {...}
    for i, v in pairs( t ) do
        print( i, v )
    end
    print("")
end
printMyArgumentsA( 1, nil, 3, nil )


-- With arg, I know how many entries there were, so I know which are nil.
local function printMyArgumentsB( ... )
    for i = 1, arg.n do
        print( i, arg[i] )
    end
    print("")
end
printMyArgumentsB( 1, nil, 3, nil )

How would I get the number of arguments sent to a function without the use of arg in later versions of Lua?


Solution

  • Use table.pack. It stores an n field, just like in the old code.

    local function printMyArgumentsB( ... )
        local arg <const> = table.pack(...)
        for i = 1, arg.n do
            print( i, arg[i] )
        end
        print()
    end
    printMyArgumentsB( 1, nil, 3, nil )
    

    If you don't want to make a table, you could use select('#', ...) to get the number of values in .... See select here.