跳转到内容

模組:NavboxV2/NavboxContext

被永久保护的模块
维基百科,自由的百科全书
-- 工具方法
function tableToString(_table)
    local outputs = {}
    if _table == nil then
        table.insert(outputs, '<nil>')
    elseif type(_table) == 'table' then
        for k, v in pairs(_table) do
            local output
            if type(v) == 'table' then
                output = tableToString(v)
            else
                output = tostring(v)
            end
            table.insert(outputs, tostring(k) .. "=" .. output)
        end
    end
    return '{' .. table.concat(outputs, ",") .. '}'
end

-- Context start
local _NavboxContext = {}
local NavboxContextNewObj = function(_prefix, _level, _type, _parent)
    return {
        ['prefix'] = _prefix,
        ['level'] = _level,
        ['type'] = _type,
        ['_Context'] = {}
    }
end

local NavboxContextMetaFunction = {
    __index = function(_obj, key)
        local _key = tostring(key)
        if _key == 'prefix' or _key == 'level' or _key == 'type' then
            return rawget(_obj, _key)
        else
            return rawget(_obj, '_Context')[_key]
        end
    end,
    __newindex = function(_obj, key, val)
        local _key = tostring(key)
        if _key == 'prefix' or _key == 'level' or _key == 'type' then
            rawset(_obj, _key, val)
        else
            rawget(_obj, '_Context')[_key] = val
        end
    end,
    __tostring = function(_obj)
        local output = {}
        table.insert(output, 'prefix=' .. _obj['prefix'])
        table.insert(output, 'level=' .. _obj['level'])
        table.insert(output, 'type=' .. _obj['type'])
        for k, v in pairs(_obj._Context) do
            local t_v = v
            if t_v == nil then
                t_v = ''
            elseif type(t_v) == 'table' then
                t_v = tableToString(t_v)
            end
            table.insert(output, k .. '=' .. t_v)
        end
        return 'context:{\n' .. table.concat(output, ",\n") .. '\n}'
    end
}

_NavboxContext.new = function(prefix, level, t_type)
    local _prefix = prefix or ""
    local _level = level or 1
    local _type = t_type or ''

    local newobj = NavboxContextNewObj(_prefix, _level, _type)
    setmetatable(newobj, NavboxContextMetaFunction)
    return newobj
end

return _NavboxContext
-- Context end