Search code examples
c#exceptionnlua

NLua handling C# Exceptions


I'm looking at NLua for scripting of an existing C# application, where C# functions called from lua may throw exceptions.

So far, I found this:

  • If the lua code does not handle an exception in a called C# function, NLua wraps and re-throws it so it can be handled at C# level.

  • If lua code does "catch" an exception via xpcall, I have found no way to access the exception's details (e.g -.Message)

The former allows me to get a debug.traceback(), a lua-level stackdump, but I don't get details of the exception. The latter provides the exception, but no way to get a Lua stackdump (I get lua file and line in .Source, but that isn't enough).

The question is:

  • Can I get details of a C# exception in a NLua "xpcall" error handler (? At least the .Message field, even better the actual exception type.

  • Alternatively, can I handle a C# exception in NLua (with the intention of creating a lua stackdump) and re-throw it?

  • Or can I get a lua stackdump somehow from the "lua state" when e.g.luaState.DoFile("myScript.lua") causes an exception?

Any help would be appreciated. NLua seems near-perfect for what I have in mind, if I could only sort out the exception handling.


Solution

  • You need to use pcall from your script. The NLua will wrap the exception and return on second value returned by pcall.

    error, exception = pcall (someFunction)
    
    if (not error) then
        print(exception.Message)
    end
    

    Example on GitHub.