table.pack()

The table.pack() function packages a variable number of arguments into a table. It also includes a field called n that indicates the number of arguments passed.

Syntax

table.pack(...)

Parameters

  • Name
    ...
    Type
    any
    Description

    A variable number of arguments to be packed into a table.

Return

The function returns a table containing the provided arguments. The table has an additional field n that holds the count of the arguments.

Description

The table.pack() function is useful for collecting multiple values into a single table. This is particularly helpful when dealing with functions that accept a variable number of arguments, allowing you to handle them as a single collection.

Examples

Packing multiple values into a table

local packedTable = table.pack(1, "Hello", true, {1, 2, 3})
print(packedTable.n)  -- Output: 4
print(packedTable[1])  -- Output: 1
print(packedTable[2])  -- Output: Hello

Handling nil values

local packedWithNil = table.pack(1, nil, 3)
print(packedWithNil.n)  -- Output: 3
print(packedWithNil[2])  -- Output: nil

Using with a variable number of arguments

local function showArgs(...)
    local args = table.pack(...)
    print("Number of arguments:", args.n)
    for i = 1, args.n do
        print("Argument " .. i .. ":", args[i])
    end
end

showArgs("A", "B", "C")  
-- Output:
-- Number of arguments: 3
-- Argument 1: A
-- Argument 2: B
-- Argument 3: C

See also

  • table.unpack(): Unpacks the values from a table back into individual arguments.

Was this page helpful?

Table of Contents