Skip to content

Commit 94c81bc

Browse files
committed
Allow hooks to throw exceptions
1 parent 70abc14 commit 94c81bc

File tree

3 files changed

+35
-6
lines changed

3 files changed

+35
-6
lines changed

src/Laylua.Tests/Tests/Moon/LuaStateTests.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,31 @@ public void FunctionNameGrabberLuaHook_GrabsFunctionNames()
111111
Assert.That(hook.FunctionNames, Is.EqualTo(new[] { "func1", "func2", "func3" }));
112112
}
113113

114+
private sealed class ThrowingLuaHook : LuaHook
115+
{
116+
protected override LuaEventMask EventMask => LuaEventMask.Count;
117+
118+
protected override int InstructionCount => 1;
119+
120+
protected override void Execute(LuaThread lua, ref LuaDebug debug)
121+
{
122+
throw new Exception(nameof(ThrowingLuaHook));
123+
}
124+
}
125+
126+
[Test]
127+
public void ThrowingLuaHook_ThrowsException()
128+
{
129+
// Arrange
130+
Lua.State.Hook = new ThrowingLuaHook();
131+
132+
// Act & Assert
133+
// Assert
134+
Assert.That(() => Lua.Execute(""), Throws.TypeOf<LuaException>()
135+
.With.InnerException.TypeOf<Exception>()
136+
.And.InnerException.Message.EqualTo(nameof(ThrowingLuaHook)));
137+
}
138+
114139
[Test]
115140
public void GC_IsRunning_ReturnsTrue()
116141
{

src/Laylua/Moon/Hook/LuaHook.cs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,6 @@ public abstract class LuaHook
2323
/// <summary>
2424
/// Invoked when this hook is triggered.
2525
/// </summary>
26-
/// <remarks>
27-
/// The code must not throw any exceptions.
28-
/// </remarks>
2926
/// <param name="lua"> The Lua state. </param>
3027
/// <param name="debug"> The debug information. </param>
3128
protected internal abstract void Execute(LuaThread lua, ref LuaDebug debug);

src/Laylua/Moon/LuaState.cs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -188,10 +188,17 @@ internal LuaHookFunction WrapHookFunction(LuaHook hook)
188188

189189
_innerHookFunction = (state, ar) =>
190190
{
191-
using (var thread = LuaThread.FromExtraSpace(state))
191+
try
192192
{
193-
var debug = new LuaDebug(thread, ar);
194-
hook.Execute(thread, ref debug);
193+
using (var thread = LuaThread.FromExtraSpace(state))
194+
{
195+
var debug = new LuaDebug(thread, ar);
196+
hook.Execute(thread, ref debug);
197+
}
198+
}
199+
catch (Exception ex)
200+
{
201+
LuaException.RaiseErrorInfo(state, "An exception occurred while executing the hook.", ex);
195202
}
196203
};
197204

0 commit comments

Comments
 (0)