lua-users home
lua-l archive

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


On 15 May 2011 20:48, Tim Menzies <tim@menzies.us> wrote:
> is the following code the best way to handle auto-initialization of nested
> table cells to zero?
>  function inc3(c,x,y,z) -- inc 3d to zero
>    c[x] = c[x] or {}
>    c[x][y] = c[x][y] or {}
>    c[x][y][z] = c[x][y][z] or 0
>    c[x][y][z] = c[x][y][z] + 1
> end
> i ask since this task is the core of  my naive bayes classifier. so it must
> be fast.
> notes: the table index names won't be known till runtime, so you can
> auto-init the data with the right names as a pre-processor.
> oh-  i've read the automagical table entry
> (http://lua-users.org/wiki/AutomagicTables) and i cant quite justify to
> myself that that approach is preferred to the above.
> but i'd like the advice of some Lua gurus!
> ADVAthanxNCE
> share and enjoy!
> :-)
> tim menzies

Perhaps:

function inc3(t, x, y, z)
    if not t[x] then t[x] = {} end
    t = t[x]
    if not t[y] then t[y] = {} end
    t = t[y]
    t[z] = (t[z] or 0) + 1
end

There might be a better way again but at least this reduces the number
of table lookups.