table.pack is very good, but I use ".n" field for other purposes. Then, I'm (seldom) using something like
pack_len = function(...)
local len = select('#',...)
return setmetatable({...},{
__len = function() return len end,
__newindex = function(t,k,v)
if math.type(k) == 'integer' then
len = math.max(len,k)
rawset(t,k,v)
end
end
})
end
t = pack_len(nil,3,nil)
print(#t, table.unpack(t))
t[10] = 3.1415
print(#t, table.unpack(t))
t[3] = 5
t[1] = 2
t[2] = 7
print(#t, table.unpack(t))
t[#t+1] = 0.5772
for i=1,#t do print(i,t[i]) end
return
as expected.