从 table 获取所有数据名称

Getting all data names from a table

我的 lua 文件中有一个嵌套的 table 全局变量,例如

GLOBAL.ADVANTAGES = 
{
CLASS =
{
    WARRIOR =
    {
        ATTACK = 0,
        DEFEND = 0,
        CRIT_CHANCE = 0,
        CRIT_DAMAGE = 0
    },
    PALADIN =
    {
        ATTACK = 0,
        DEFEND = 0,
        CRIT_CHANCE = 0,
        CRIT_DAMAGE = 0
    },
    PRIEST =
    {
        ATTACK = 0,
        DEFEND = 0,
        CRIT_CHANCE = 0,
        CRIT_DAMAGE = 0
    },
    ...
...

我想遍历table到return字符串中的所有变量名,如"GLOBAL.CLASS.PRIEST.ATTACK"、"GLOBAL.CLASS.PRIEST.DEFENSE"等。我已经可以遍历整个 table 但它 return 的值仅作为 "ATTACK"、"DEFENSE" 等等...

如何获得每个值的完整 "address"?

假设您正在进行深度优先遍历(又名按顺序),当您降低层次结构时,向下传递父节点的 path。在捕获叶子名称的位置,在其前面加上父节点的路径。如果节点不是叶节点,则在节点名称前加上父节点的路径并向下传递。

local node = path .. "." .. tostring(key) -- tostring used in case key is not a string

使用"GLOBAL"作为初始路径。

更高效、更简单的方法是使用 table.concat。例如,要显示所有字段:

local myprint
myprint = function(tab, prefixtab) -- Tab = tab to print, prefix = inital tab ({'GLOBAL'} in your case) or nil
    prefixtab = prefixtab or {}
    local idx = #prefixtab+1
    for k,v in pairs(tab) do
        prefixtab[idx] = k
        print(table.concat(prefixtab, '.')) -- Comment to don't print for every path
        if type(v) == 'table' then
            myprint(v, prefixtab)
        --else -- To print only complete pathes
            --print(table.concat(prefixtab, '.'))
        end
    end
    prefixtab[idx] = nil
end

示例(基于您的table):

> myprint(GLOBAL, {'GLOBAL'})
GLOBAL.ADVANTAGES
GLOBAL.ADVANTAGES.CLASS
GLOBAL.ADVANTAGES.CLASS.WARRIOR
GLOBAL.ADVANTAGES.CLASS.WARRIOR.CRIT_DAMAGE
GLOBAL.ADVANTAGES.CLASS.WARRIOR.ATTACK
GLOBAL.ADVANTAGES.CLASS.WARRIOR.CRIT_CHANCE
GLOBAL.ADVANTAGES.CLASS.WARRIOR.DEFEND
GLOBAL.ADVANTAGES.CLASS.PRIEST
GLOBAL.ADVANTAGES.CLASS.PRIEST.CRIT_DAMAGE
GLOBAL.ADVANTAGES.CLASS.PRIEST.ATTACK
GLOBAL.ADVANTAGES.CLASS.PRIEST.CRIT_CHANCE
GLOBAL.ADVANTAGES.CLASS.PRIEST.DEFEND
GLOBAL.ADVANTAGES.CLASS.PALADIN
GLOBAL.ADVANTAGES.CLASS.PALADIN.CRIT_DAMAGE
GLOBAL.ADVANTAGES.CLASS.PALADIN.ATTACK
GLOBAL.ADVANTAGES.CLASS.PALADIN.CRIT_CHANCE
GLOBAL.ADVANTAGES.CLASS.PALADIN.DEFEND

或完整路径版本:

> myprint(GLOBAL, {'GLOBAL'})
GLOBAL.ADVANTAGES.CLASS.PRIEST.CRIT_CHANCE
GLOBAL.ADVANTAGES.CLASS.PRIEST.ATTACK
GLOBAL.ADVANTAGES.CLASS.PRIEST.CRIT_DAMAGE
GLOBAL.ADVANTAGES.CLASS.PRIEST.DEFEND
GLOBAL.ADVANTAGES.CLASS.WARRIOR.CRIT_CHANCE
GLOBAL.ADVANTAGES.CLASS.WARRIOR.ATTACK
GLOBAL.ADVANTAGES.CLASS.WARRIOR.CRIT_DAMAGE
GLOBAL.ADVANTAGES.CLASS.WARRIOR.DEFEND
GLOBAL.ADVANTAGES.CLASS.PALADIN.CRIT_CHANCE
GLOBAL.ADVANTAGES.CLASS.PALADIN.ATTACK
GLOBAL.ADVANTAGES.CLASS.PALADIN.CRIT_DAMAGE
GLOBAL.ADVANTAGES.CLASS.PALADIN.DEFEND