lua-users home
lua-l archive

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


On Sun, May 15, 2011 at 02:56:03PM +0200, Mason Larobina wrote:
> 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.

If t[x][y] already exists then this code has 6 lookups; if t[x], 7; 
if t only, 8; if not even t, there is an error, as there should be.

The following code reduces 6,7,8 to 4,5,6.

function inc3(t, x, y, z)
    local tx = t[x]
    if not tx then tx={}; t[x] = tx end
    local txy = tx[y]
    if not txy then txy={}; tx[y] = txy end
    local txyz = txy[z];
    if not txyz then txy[z]=1 else txy[z]=txyz+1 end
end

Dirk