2011-11-24 38 views
2

我目前正在尝试为朋友编写流行游戏“魔兽世界”的附加代码。我不太了解游戏本身,而且在游戏中进行调试很困难,因为他必须进行所有测试。以干净有效的方式处理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是零的时候时,它仍然抛出约试图调用P1作为零一个Lua错误。它有时无,这需要正确处理。

什么是正确的最有效的方式去做这件事?

+0

你是说,如果'p1'是'nil',它进入'else'条款?因为这似乎不太可能。你确定你没有从其他地方得到错误吗? –

回答

4

您可能想要将您的函数封装在pcallxpcall中,这样您可以截获Lua抛出的任何错误。除了那

,我个人认为,这一构造更容易阅读:

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