lua-users home
lua-l archive

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


2010/4/24 "J.Jørgen von Bargen" <jjvb.primus@gmx.de>:
> 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.
>

The obvious approach is to effectively make your ta function the
__index metamethod for the lookup table:

local lookup = setmetatable({}, {__index = function(t, k)
  local v = {}
  t[k] = v
  return v
end})

Then just do:

local data = lookup[item]