2016-03-01 60 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