Search code examples
lualua-table

How to mimic Lua's table.pack() without `n` key


I'm trying to rewrite my own tablePack() function that returns a table without n.

For example, calling tablePack(1, 2, 3) should return a table {1, 2, 3}.

How can I create the tablePack() function? Any advice would be appreciated.


ADDED:

Here's an example code:

local a = table.pack(1,2,3)
local b = {1,2,3}

print(a.n, b.n)

Result:

3   nil

How can I create my own tablePack() function so the result can be the following?

nil  nil

ADDED2:

Would this be the solution?

function tablePack(...)
  local r = table.pack(...)
  r.n = nil
  return r;
end

Maybe this is better?

function ofTable(...)
  return {...}
end

Solution

  • Your ofTable solution is best.

    table.pack is useful when some of the arguments may be nil. The n field would let you either detect trailing nils contained within the ... or cope with the fact that #, ipairs, and most table functions won't work.