Lua - 检查数组是否存在

3

我正在尝试通过if语句查找特定数组是否存在,例如

if array{} == nil then array = {} else print("it exists") end

上面的方法似乎不起作用,而且我也没有办法检查它是否存在。基本上,我正在创建一个插件,用于扫描特定事件的日志,如果事件为真,则返回法术名称。我希望使用该法术名称创建一个数组,但是“spellName = {}”不起作用,因为它似乎只会创建一个新数组(而不是更新现有数组)。

local _SPD = CreateFrame("Frame");
_SPD:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED");
_SPD:SetScript("OnEvent", function(self, event, ...)

local timestamp, type, sourceName = select(1, ...), select(2, ...), select(5, ...)

if (event == "COMBAT_LOG_EVENT_UNFILTERED") then
    if select(2,...) == "SPELL_AURA_APPLIED" then
        if select(5,...) == UnitName("player") then

            local spellID, spellName = select(12, ...), select(13, ...)

             spellName = { 
                sourceName = {

                } 
            }

            table.insert(spellName["sourceName"], {id = spellID, stamp = timestamp })

            for k,v in pairs ( spellName["sourceName"] ) do
                print (k.. ": " ..v["id"].. " at " ..v["stamp"])
            end 
        end
    end
end
end);

基本上,每次在我身上施加某种光环时(这是预期行为),都需要重新创建表。
我已经尝试了很多方法,但不知道如何检查spellName(和sourceName)是否存在,如果存在,则不创建它们,因为在这种情况下变量已经存在并返回值给我,因此我无法检查它们是否为空,因为它们不会为空,我需要以某种方式检查这些值上是否存在表,如果不存在则创建它们。
提前感谢。

1
本地变量spellID和spellName的赋值方式local spellID, spellName = select(12, ...), select(13, ...)是愚蠢的。去掉, select(13, ...),只留下select(12, ...)即可。select()实际上返回从给定索引开始的所有值,而不仅仅是单个值,因此说local a, b = select(12, ...)将把第12个参数分配给a,第13个参数分配给b - Lily Ballard
@KevinBallard,那应该能为我节省一些空间,谢谢。 - sof2er
2个回答

2
您的表格检查声明不正确。请按如下方式使用:
if type(array) == "table" then
  print("it exists")
else
  array = {}
end

1
说句实话,这可以写成 array = type(array) == "table" and array or {} - furq
你本可以只写成 if type(array) == 'table' then -- 这样如果 array 为 nil,它会返回 nil,使第一个测试变得不必要。 - Mud
@Mud 嗯,我不知道 type 可以接受 nil 参数。已编辑。 - hjpotter92
你需要使用 if type(spellName) == "table" 作为你的if条件。 - hjpotter92
啊哈!它一直提示在相同的拼写上创建,而应该在后续运行中显示“存在”。我完全不知道为什么。 - sof2er
显示剩余3条评论

1

试试这个:

local spellID, spellName = select(12, ...), select(13, ...)
spellName = spellName or {}
spellName.sourceName = spellName.sourceName or {}
table.insert(spellName.sourceName, {id = spellID, stamp = timestamp })

不幸的是,它没有起作用,返回了一个错误 Locals: (*temporary) = nil (*temporary) = <table> { id = 52127 stamp = 1359598562.074 } (*temporary) = "table expected, got nil" - sof2er
@user2026598 - 我已经编辑了我的答案。请再试一次。 - Egor Skriptunoff
似乎也不起作用,但在顶部添加myTable = {}并使用if myTable [spellName] then print(“exists”)else myTable [spellName] = {} end似乎解决了问题。感谢此线程中的以下人员:http://www.mmo-champion.com/threads/1257678-LUA-Arrays-detection-%28on-a-variable-returned-as-string%29 - sof2er

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接