lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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

3    nil    3    nil
10    nil    3    nil    nil    nil    nil    nil    nil    nil    3.1415
10    2    7    5    nil    nil    nil    nil    nil    nil    3.1415
1    2
2    7
3    5
4    nil
5    nil
6    nil
7    nil
8    nil
9    nil
10    3.1415
11    0.5772

as expected.

This keep symmetry with table.pack, as well as others table.something, and give me an unbounded "sparse array" with well defined length.

There is something wrong with this implementation?



2016-07-22 4:06 GMT-03:00 steve donovan <steve.j.donovan@gmail.com>:
On Fri, Jul 22, 2016 at 1:54 AM, Tim Hill <drtimhill@gmail.com> wrote:
> But that would still leave the general case of {f()} unsolved :(

We always have table.pack(f()) ...

Especially when pack/unpack become symmetrical.




--
Rodrigo Azevedo Moreira da Silva