Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua unpack() messing arguments

Tags:

lua

I have this test function which simply prints values passed to it

function test1(...)
  for k, v in ipairs(arg) do
    print(v)    
  end
end

function test2(...)
  for k, v in pairs(arg) do
    print(v)    
  end
end

-- GOOD behavior
test1(1, 2, 3, 4) -- produces 1 2 3 4
test2(1, 2, 3, 4) -- produces 1 2 3 4

-- BAD behavior
test1( unpack({1,2}), 3, 4) -- produces 1 3 4
test2( unpack({1,2}), 3, 4) -- produces 1 3 4 3

Can someone explain this behavior to me ?

like image 432
lukas.pukenis Avatar asked Apr 27 '15 09:04

lukas.pukenis


1 Answers

This behavior is not specific to unpack. The Lua Reference Manual says:

"Both function calls and vararg expressions can result in multiple values. If a function call is used as a statement (see §3.3.6), then its return list is adjusted to zero elements, thus discarding all returned values. If an expression is used as the last (or the only) element of a list of expressions, then no adjustment is made (unless the expression is enclosed in parentheses). In all other contexts, Lua adjusts the result list to one element, either discarding all values except the first one or adding a single nil if there are no values."

(my emphasis)

like image 78
lhf Avatar answered Nov 03 '22 07:11

lhf