lua-users home
lua-l archive

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


The metatable __index suggestion is probably the neatest and fastest one so far (and it's the way i've done this sort of thing myself in the past), but I'm curious, is there a reason why you didn't consider:

local data = lookup[item]
if (data == nil) then data = {} lookup[item] = data; end

It violates the "try and make the line as short and cryptic as possible" rule but it should avoid the unnecessary assignment quite neatly, and it's simple.

Daniel.



On 4/24/10 7:53 AM, "J.Jørgen von Bargen" wrote:
Hi, folks
I'm looking for a better idiom for

    -- initial
    local lookup={}
    --

    for item in item_source() do
        -- vv this is the uggly code
        local data=lookup[item] or {}
        lookup[item]=data
        -- ^^ this is the uggly code

        -- do something more with data, e.g.
        data.set=true
        data.count=(data.count or 0)+1
        --
    end

(Where item_source will return about 20 different items about 1000 times in random order)

I have replaced it with

local function ta(t,a)
    local n={}
    t[a]=n
    return n
end

       -- vv better code
       local data=lookup[item] or ta(lookup,item)
       -- ^^ better code

eliminating multiple assigns to lookup[item], which already gave me a speedup of about 11%. Any suggestions to make it even faster or prettyer (and without a function call?)

Regards Jørgen

PS: This is not the real code, but I come across this quite often and like to do it the best way.