lua-users home
lua-l archive

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


Oh, that actually might work!

Heres my complete Hack:
------//-----
local aStack = {}
local aStackN = 0

local autoMeta = {
    __index = function(t, k)
        aStack[0] = t
        aStack[1] = k
        aStackN = 1
        return nil
    end
}

function newAutoTable()
    return setmetatable({}, autoMeta)
end

debug.setmetatable(nil, {
    __index= function (_, k)
        aStackN = aStackN + 1;
        aStack[aStackN] = k
        return nil
    end,
    __newindex = function(_, k, v)
        local t = aStack[0]
        for i = 1,aStackN do
            local nat = newAutoTable()
            t[aStack[i]] = nat
            t = nat
        end
        t[k] = v
        aStackN = 0
        aStack = {} -- (optional reset to free for GC)
    end
})
------//-----
testcase:
------//-----
$ lua
Lua 5.1.3  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> dofile("autotable.lua")
> a = newAutoTable()
> = a.b.c.d
nil
> = a.b.c
nil
> a.b.c.d = "mx"
> = a.b.c.d
mx
> = a.b.c
table: 0x87bebf0
------//-----

Personally not quite my style to use it in a larger project, since I
like pedantic error raising to detect coding errors rather sooner than
later having to debug. That way indexing of nil is now valid, it will
run over other bad code not connected to AutoTables, where it would've
complained before. Nevertheless, nice proof of concept :-)

Since
badspelling.x.y.z = "ma"
will no longer raise any error, when not caught by __index in _G one
could go for the whole fluff, by also setting __index of _G to
autoMeta.__index

Kind regards,
Axel