2011-11-24 95 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