2016-03-01 88 views
1

是否有可能從函數中拋出一個Lua錯誤,由調用函數的腳本來處理?如何拋出Lua錯誤?

例如下面將拋出一個錯誤,在指定的評論

local function aSimpleFunction(...) 
    string.format(...) -- Error is indicated to be here 
end 

aSimpleFunction("An example function: %i",nil) 

但我寧願做的是捕獲錯誤並通過函數調用拋出了一個自定義錯誤

local function aSimpleFunction(...) 
    if pcall(function(...) 
     string.format(...) 
    end) == false then 
     -- I want to throw a custom error to whatever is making the call to this function 
    end 

end 

aSimpleFunction("An example function: %i",nil) -- Want the error to start unwinding here 

的意圖是在我的實際使用情況下,我的功能會更加複雜,我想提供更有意義的錯誤消息

+2

的例子[Lua代碼可以顯式地通過調用誤差函數產生一個錯誤。](http://www.lua.org/manual/5.3/manual .html#2.3) –

+0

@TomBlodget,讓它成爲答案? ;) –

+0

@PaulKulchenko - 似乎寫評論而不是答案的想法是相當具有傳染性的;-) –

回答

1

堆棧水平的錯誤可以在拋出新錯誤時指定

error("Error Message") -- Throws at the current stack 
error("Error Message",2) -- Throws to the caller 
error("Error Message",3) -- Throws to the caller after that 

通常,錯誤會在消息的開頭添加有關錯誤位置的一些信息。 level參數指定如何獲取錯誤位置。通過級別1(默認值),錯誤位置是調用錯誤函數的位置。級別2將錯誤指向調用錯誤的函數調用的位置;等等。通過級別0可避免在消息中添加錯誤位置信息。

使用在給定的問題

local function aSimpleFunction(...) 
    if pcall(function(...) 
     string.format(...) 
    end) == false then 
     error("Function cannot format text",2) 
    end 

end 

aSimpleFunction("An example function: %i",nil) --Error appears here 
-1

捕獲的錯誤是使用pcall

My_Error() 
    --Error Somehow 
end 

local success,err = pcall(My_Error) 

if not success then 
    error(err) 
end 

毫無疑問,你問這是如何工作的那麼簡單。那麼pcall受保護的線程(受保護的調用)中運行一個函數並返回一個bool(如果它成功運行)和一個值(它返回的/錯誤)。

也並不認爲這意味着函數的自變量是不可能的,只是把它們傳遞給pcall還有:

My_Error(x) 
    print(x) 
    --Error Somehow 
end 

local success,err = pcall(My_Error, "hi") 

if not success then 
    error(err) 
end 

更多的錯誤處理的控制,看http://www.lua.org/manual/5.3/manual.html#2.3http://wiki.roblox.com/index.php?title=Function_dump/Basic_functions#xpcall