There are some
.NET methods which will throw exceptions on error. These are
converted into regular Lua errors by LuaInterface, so you need to
execute these methods in a protected call to
avoid your program crashing. For instance, load_assembly
usually loads
assemblies from the Global Assembly Cache (GAC) but it will work
with your own assemblies if you end them with an explicit
'.dll'.
However, it will not load an assembly given an arbitrary path. This is not difficult to get around, but the function we need is one of those that throw exceptions. Consider this script:
-- load.lua
require "CLRPackage"
import "System.Reflection"
function get_assembly_name(name)
local res
local suc,err = pcall(function()
res = AssemblyName.GetAssemblyName(name)
end)
if suc then
return res
else
return nil,err
end
end
print(get_assembly_name(arg[1]))
GetAssemblyName
returns
an object which you can pass to Assembly.Load
, but we have to
call it using pcall
.
pcall
will usually
just return true
, but if an
error occured it returns false,error
. In
effect, this is Lua's try..catch
mechanism. The
variable err will contain the exception thrown and the message from
the exception in string format.