【问题标题】:Lua - check if array existsLua - 检查数组是否存在
【发布时间】:2013-01-14 17:32:26
【问题描述】:

我正在尝试通过 if 语句(例如

)找出某个数组是否存在
if array{} == nil then array = {} else print("it exists") end

上面似乎不起作用,我无法检查它是否存在,基本上我正在创建一个插件,它会扫描日志以查找某个事件,如果它是真的,它会返回拼写名称。我希望使用该 spellName 创建一个数组,但是 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)是否存在,如果存在则不要再次创建它们,因为在这种情况下,变量已经存在,因为它会将值返回给我,所以我可以'不检查它们是否为零,因为它们不会,我需要以某种方式检查这些值上是否存在表,如果不创建它们。

提前致谢。

【问题讨论】:

  • local spellID, spellName = select(12, ...), select(13, ...) 很傻。摆脱, select(13, ...) 并留下select(12, ...)。 select() 实际上返回所有值,从给定索引开始,而不仅仅是单个值,所以说local a, b = select(12, ...) 会将第 12 个参数分配给a,将第 13 个参数分配给b。
  • @KevinBallard,这应该可以为我节省一些空间,谢谢。

标签: arrays string lua


【解决方案1】:

您的 table 检查声明是错误的。像这样使用它:

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

【讨论】:

  • 对于它的价值,这可以写成array = type(array) == "table" and array or {}。
  • 你可以直接写if type(array) == 'table' then——如果数组为nil,它将返回nil,这样就不需要第一次测试了。
  • @Mud 嗯,我不知道type 可以接受零参数。已编辑。
  • 感谢您的帮助,我添加了以下几行:print(spellName) if type(array) == spellName then print("it exists") else spellName = {} print(spellName) print("created") end 并且它似乎返回了带有 spellName 的第一个打印,但创建表后的打印返回一个表号(每次我运行咒语时都会有所不同,而第一次打印保持不变。
  • 你需要使用if type(spellName) == "table"作为你的if条件。
【解决方案2】:

试试这个:

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"
  • @user2026598 - 编辑了我的答案。请再试一次。
  • 似乎也不起作用,但是在顶部添加 myTable = {} 并使用 if myTable[spellName] then print("exists") else myTable[spellName] = {} end 似乎可以解决问题。感谢此线程中的以下人员:mmo-champion.com/threads/…
猜你喜欢
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 2010-11-23
  • 2011-06-26
  • 1970-01-01
  • 2013-03-03
相关资源
最近更新 更多