Lua类型的嵌套表引用函数。

我刚开始为魔兽世界写Lua代码。我经常需要检查一个嵌套在表格中的全局变量是否已由其他作者的Lua代码定义。

例如:

Mytable[MyfirstLvl].Mysecondlvl.fred 其中变量MyfirstLvl中包含空格

目前我正在使用:

if (type(Mytable) == 'table') and (type(Mytable[MyfirstLvl]) == 'table') and (type(Mytable[MyfirstLvl].Mysecondlvl) == 'table') then
    --some code using Mytable[MyfirstLvl].Mysecondlvl.fred
end

我希望有一个更简单的方法来做到这一点。我想过编写一个使用_G的函数,但找不到任何解析其中带有“['']”和“['']”的动态变量名称的示例。

是否有一种简单的方法来判断表格中嵌套数层的值是否已定义,或者有没有人可以帮助创建一个自定义函数来完成此操作?

以下是我的想法:

function newType(reference)
    if type(reference) ~= 'string' then
        print('...argument to Type must be a string')
        return
    end

    local t = {string.split('].[', reference)}

    local tt = {}
    for k, v in ipairs(t) do
        if string.len(v) ~= 0 then
            local valueToInsert = v
            if (string.sub(v, 1, 1) == '"') or (string.sub(v, 1, 1) == "'") then
                valueToInsert = string.sub(v, 2, -2)
            elseif tonumber(v) then
                valueToInsert = tonumber(v)
            end
            table.insert(tt, valueToInsert)
        end
    end

    local myReference = _G
    local myType
    for i, curArg in ipairs(tt) do
        if type(myReference) ~= 'table' then
            return 'nil'
        end
        if type(myReference[curArg]) ~= 'nil' then
            myReference = myReference[curArg]
            myType = type(myReference)
        else
            return 'nil'
        end
    end
    return myType

end
SavedDB = {}
SavedDB.profiles = {}
SavedDB.profiles.Character = {}
SavedDB.profiles.Character.name = '火热的梅林'
print(newType('SavedDB.profiles["Character"].name')

你们所有的评论帮助我思考这个问题。谢谢。如果你们发现了一个更好的方法来完成这个任务(我希望下面的示例能帮助),请告诉我。我想编写一个函数,只需要传递一个字符串即可,但是当字符串包括["Character"]时,无法让模式匹配起作用。

点赞
用户204011
用户204011

你觉得这样行吗?

如果类型为:"table"

if type( ((Mytable or {})[MyfirstLvl] or {}).Mysecondlvl ) == "table"
2013-11-28 18:07:58