recursionlualua-table

Repacking or printing unpacked Lua tables


Why does the table.unpack() function print the unpacked table only if there is nothing following the function?

> print(table.unpack({1,2,3}))
1       2       3

> print(table.unpack({1,2,3}),"a")  -- expecting: 1       2       3       a
1       a

> print("a",table.unpack({1,2,3}))
a       1       2       3

Background: I am trying to create a recursive function that unpacks a table, inserts a value, and repacks it to return a table with the new value. This works when you do something like table.pack("a", table.unpack({1,2,3})) but not when you do table.pack(table.unpack({1,2,3}), "a").


Solution

  • I once fell in the same trap.

    When a multires expression is used in a list of expressions without being the last element, or in a place where the syntax expects a single expression, Lua adjusts the result list of that expression to one element.

    Lua 5.4 manual. 3.4.12 – Lists of expressions, multiple results, and adjustment.

    So, table.unpack(…) or ... should be last in a list of expressions.

    Perhaps, if you literally want to insert some values into a table, you could use table.insert()?