【问题标题】:How do you throw Lua error up?你如何抛出 Lua 错误?
【发布时间】:2025-12-23 09:15:17
【问题描述】:

是否可以从函数中抛出 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 

目的是在我的实际用例中我的功能会更复杂,我想提供更有意义的错误消息

【问题讨论】:

  • @TomBlodget,让它成为答案? ;)
  • @PaulKulchenko - 似乎写 cmets 而不是答案的想法很有感染力 ;-)
  • @EgorSkriptunoff,我注意到了 ;)
  • @PaulKulchenko 我宁愿看到这个问题被删除而不是写一个答案。但是,我确实想帮助提问者了解可理解的文档(Lua 参考手册是)是主要参考。我不认为这个问题及其任何直接答案对其他人有帮助。如果问题更广泛,那么他们会。

标签: error-handling lua throw


【解决方案1】:

使用error function

error("something went wrong!")

【讨论】:

    【解决方案2】:

    捕捉错误就像使用pcall一样简单

    My_Error()
        --Error Somehow
    end
    
    local success,err = pcall(My_Error)
    
    if not success then
        error(err)
    end
    

    毫无疑问,您是在问这是如何工作的。 pcall受保护的线程(受保护的调用)中运行一个函数,如果运行成功,则返回一个布尔值,以及一个值(返回的内容/错误)。

    也不要认为这意味着函数的参数是不可能的,只需将它们也传递给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

    【讨论】:

      【解决方案3】:

      抛出新错误时可以指定错误的堆栈级别

      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
      

      通常,error 会在消息的开头添加一些关于错误位置的信息。 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 
      

      【讨论】: