【问题标题】:Handling Lua errors in a clean and effective manner以干净有效的方式处理 Lua 错误
【发布时间】:2011-11-24 17:39:22
【问题描述】:

我目前正在尝试为一个朋友编写一个热门游戏《魔兽世界》的插件。我自己对游戏了解不多,在游戏中调试很困难,因为他必须做所有的测试。

我对 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 错误。有时它会为零,这需要正确处理。

解决此问题的正确最有效方法是什么?

【问题讨论】:

  • 您是说如果p1nil,它会进入else 子句吗?因为这似乎不太可能。你确定你没有从其他地方收到错误吗?

标签: error-handling lua custom-error-handling


【解决方案1】:

您可能希望将函数包装在 pcallxpcall 中,这样您就可以拦截 Lua 抛出的任何错误。

除此之外,我个人觉得这个结构更容易阅读:

p1=string.match(str,pat)
if p1 then
    -- p1 is valid, eg not nil or false
else
    -- handle the problems
end

【讨论】:

    猜你喜欢
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多