Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

Unpacking table in a function call

Without giving too much details, this sample snippet demonstrates the problem:

-- Add an extra predefined argument
function one_more_arg(...)                                                                        
    local args = {...}
    return function()
        print(table.unpack(args), "c")
    end
end

local my_new_print = one_more_arg("a", "b")
my_new_print()  -- "a   c"

Apparently unpacking a table does not work in this scenario. Any ideas on how to make this work, ie print will receive "a", "b", "c"? I'm trying to avoid modifying args, unless it's the only way to achieve it.

Upvotes: 2

Views: 1452

Answers (2)

ephemerr
ephemerr

Reputation: 1983

When you place table.unpack() as an argument to function there should be no other arguments or it should be the last one. Otherwise only first value from table will be passed.

Lua always adjusts the number of results from a function to the circumstances of the call. When we call a function as a statement, Lua discards all of its results. When we use a call as an expression, Lua keeps only the first result. We get all results only when the call is the last (or the only) expression in a list of expressions. These lists appear in four constructions in Lua: multiple assignment, arguments to function calls, table constructors, and return statements.

From http://www.lua.org/pil/5.1.html

So you can try to put unpack at the end if it is ok for you:

print("c", table.unpack(args))

Or modify args.

Upvotes: 4

Syabro
Syabro

Reputation: 65

table.concat (list [, sep [, i [, j]]])

Given a list where all elements are strings or numbers, returns the string list[i]..sep..list[i+1] ··· sep..list[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is #list. If i is greater than j, returns the empty string.

Upvotes: -1

Related Questions