Search code examples
lualua-table

Purpose of `n` field added to tables by `table.pack`? Heck, why does `table.pack` even exist?


Title says it all. I want to know why Lua adds an n field to tables when using table.pack().

Literally this is how you can implement this:

function pack(...)
    return { n = select("#", ...), ... }
end

-- pretty useless

I don't see a point as you can use {} to construct a table and #tbl to get how many elements there are in a table.

local tbl = table.pack('a', 'b', 'c', 'd')
print(tbl.n, #{ 'a', 'b', 'c', 'd' }) -- 4    4

-- Same thing

If you use next to traverse a table constructed with table.pack, it really ruins iteration. Ofc you can use ipairs but for those who don't? Oh and length operator won't count that n.


Solution

  • table.pack() need not return a sequence. It only does so iff all arguments are non-nil.

    Thus, if you want to reverse it, you need the "n"-member in the general case.

    table.unpack(t, 1, t.n)
    

    And despite the implementation being pretty trivial, table.pack() is still a useful abstraction.