如何在C#中捕获Lua异常

我正在使用一个名为 LuaInterface 的程序集在我的 C# 应用程序中运行 Lua 代码。在 Lua 执行期间,我创建一些 WinForms 并将事件处理程序(Lua 方法)映射到它们。

问题在于 doString 方法(又称 runLuaCode)仅运行初始程序和构造函数。这很好和预期,但是 doString 函数的操作是非阻塞的,因此函数返回时,Lua 创建的 Forms 仍然存在。这意味着任何未在构造函数期间引发的异常(例如 null-ref)都没有被 Lua 错误处理处理,因此会崩溃到我的 Editor 的 wndProc,这可能会导致我的编辑器崩溃,并且使错误处理几乎不可能。

有没有办法创建一个新的线程 / 进程 / AppDomain,以处理自己的 WndProc,从而只需处理这个子任务即可处理异常?

我应该在 doString 中使用 while 循环在 Lua 中阻塞我的 Editor 直到关闭表单吗?

我还有哪些其他选项?

关于这个问题的任何建议都将不胜感激!

原文链接 https://stackoverflow.com/questions/4942346

点赞
stackoverflow用户621390
stackoverflow用户621390

另一个 Lua 爱好者!! 终于有人了!:) 我也在考虑在我的 .NET 应用程序中使用 Lua 进行宏脚本编写。

我不确定是否理解正确。我编写了一些示例代码,似乎工作正常。将 DoString 包装在简单的 try catch 语句块中可获取 LuaExceptions。DoString 会阻塞主线程,除非你显式创建一个新线程。在创建新线程的情况下,常规的 .NET 多线程异常处理规则适用。

示例:

public const string ScriptTxt = @"
luanet.load_assembly ""System.Windows.Forms""
luanet.load_assembly ""System.Drawing""

Form = luanet.import_type ""System.Windows.Forms.Form""
Button = luanet.import_type ""System.Windows.Forms.Button""
Point = luanet.import_type ""System.Drawing.Point""
MessageBox = luanet.import_type ""System.Windows.Forms.MessageBox""
MessageBoxButtons = luanet.import_type ""System.Windows.Forms.MessageBoxButtons""

form = Form()
form.Text = ""Hello, World!""
button = Button()
button.Text = ""Click Me!""
button.Location = Point(20,20)
button.Click:Add(function()
        MessageBox:Show(""Clicked!"", """", MessageBoxButtons.OK) -- this will throw an ex
    end)
form.Controls:Add(button)
form:ShowDialog()";

        private static void Main(string[] args)
        {
            try
            {
                var lua = new Lua();
                lua.DoString(ScriptTxt);
            }
            catch(LuaException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch(Exception ex)
            {
                if (ex.Source == "LuaInterface")
                {
                    Console.WriteLine(ex.Message);
                }
                else
                {
                    throw;
                }
            }

            Console.ReadLine();
        }

LuaInterface 有非常好的文档,解释了复杂的错误处理。

http://penlight.luaforge.net/packages/LuaInterface/#T6

希望会有所帮助。 :)

2011-02-22 13:44:36