gpt4 book ai didi

c# - 如何在 C# 中捕获 Lua 异常

转载 作者:行者123 更新时间:2023-11-30 13:05:25 26 4
gpt4 key购买 nike

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

问题是 doString(又名 runLuaCode)方法只运行 init 例程和构造函数。这很好并且是有意的,但是 doString 函数是非阻塞的,所以函数返回时 Lua-created-Forms 仍然存在。这意味着在构造函数期间未引发的任何异常(null-ref 等)都不会由 lua 错误处理一直崩溃到我的编辑器的 wndProc - 这很可能会杀死我的编辑器并进行错误处理几乎不可能。

有没有办法创建一个新的线程/进程/AppDomain 来处理它自己的 WndProc,以便只有这个子任务需要处理异常?

我是否应该在 doString 中用 lua 中的 while 循环阻止我的编辑器直到表单关闭?

我还有哪些其他选择?

非常感谢关于此事的任何建议!

最佳答案

又一个 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

希望对你有所帮助。 :)

关于c# - 如何在 C# 中捕获 Lua 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4942346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com