清洁有效地处理Lua错误

我正在尝试为朋友编写流行游戏《魔兽世界》的附加组件。我对游戏了解有限,在游戏中调试困难,因为他必须进行所有测试。

我对 Lua 还比较陌生,所以这可能是一个非常容易回答的问题。但是,当 WoW 中出现 Lua 错误时,它会在屏幕上抛出错误并阻碍游戏体验,这对于游戏玩家来说非常糟糕,因为它会在错误时间抛出异常并停止游戏。我正在寻找一种优雅地处理抛出的错误的方法。这是我的函数目前的代码。

function GuildShoppingList:gslSlashProc()
    -- Actions to be taken when command /gsl is procced.
    BankTab = GetCurrentGuildBankTab()
    BankInfo = GetGuildBankText(BankTab)
    local Tabname, Tabicon, TabisViewable, TabcanDeposit, TabnumWithdrawals, remainingWithdrawals = GetGuildBankTabInfo(BankTab)
    p1 = BankInfo:match('%-%- GSL %-%-%s+(.*)%s+%-%- ENDGSL %-%-')
    if p1 == nil then
        self:Print("GSL could not retrieve information, please open the guild bank and select the info tab allow data collection to be made")
    else
        self:Print("Returning info for: "..Tabname)
        for id,qty in p1:gmatch('(%d+):(%d+)') do
            --do something with those keys:
            local sName, sLink, iRarity, iLevel, iMinLevel, sType, sSubType, iStackCount = GetItemInfo(id);
            local iSum = qty/iStackCount
            self:Print("We need "..sLink.." x"..qty.."("..iSum.." stacks of "..iStackCount..")")
        end
    end
end

问题在于,在检查 p1 是否为 nil 时,它仍会抛出一个关于尝试将 p1 作为 nil 调用的 Lua 错误。它有时将是 nil,这需要正确处理。

如何以最正确和有效的方式处理这个问题?

点赞
用户513763
用户513763

你可能想使用 pcall 或者 xpcall 来包装你的函数,这样可以让你捕捉到 Lua 抛出的所有错误。

除此之外,我个人觉得这种写法更易于阅读:

p1=string.match(str,pat)
if p1 then
    -- p1 是有效的,例如不为 nil 或者 false
else
    -- 处理问题
end
2011-11-24 08:30:37