Lua,如何访问使用数组的索引

如何检查索引内部的数组 [{4, 8}] 以确认 'vocation',即 8 是否存在?

local outfits = {
    [7995] = {
            [{1, 5}] = {94210, 1},
            [{2, 6}] = {94210, 1},
            [{3, 7}] = {94210, 1},
            [{4, 8}] = {94210, 1}
    }
}

local item = 7995
local vocation = 8

if outfits[item] then
    local index = outfits[item]
    --for i = 1, #index do
    --  for n = 1, #index[i]
    --  if index[i]
    -- ????
end
点赞
用户7396148
用户7396148

你只需要使用 pairs 而不是基本的循环迭代即可。使用 pairs,你将获得你的键值对,然后可以循环遍历键来检查其内容。

local found = 0

if outfits[item] then
    local value = outfits[item]
    for k, v in pairs(value) do
        for n = 1, #k do
            if k[n] == vocation then
                found = k
                break;
            end
        end
    end
end
print(outfits[item][found][1])

尽管如此,这不是存储查找值的非常有效的方法,而且不适用于记录更多的情况。

2020-06-16 21:44:48