lua-users home
lua-l archive

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


2009/7/16 Javier Guerra <javier@guerrag.com>:
> On Thu, Jul 16, 2009 at 3:50 PM, Cosmin
> Apreutesei<cosmin.apreutesei@gmail.com> wrote:
>> Anything that could conflict with such changes?
>
> performance.   #t would decay into a O(n) operation

And without a single change to Lua itself you can add support for
sparse arrays with a couple functions:

function pack(...)
    return {['#'] = select('#', ...), ...}
end

local _unpack = unpack
function unpack(t, i, j)
    return _unpack(t, i, j or t['#'])
end

-- example
local function foo(skip1, skip2, ...)
    return pack(...)
end

print(unpack(foo(1, 2, 3, nil, 5, 6, nil, nil)))
--> 3       nil     5       6       nil     nil

If necessary you can even avoid putting the length in the array itself
(in the example above at the key '#') with the help of a weak table.