Lua 接口 |
|
接口是一个用于 Lua 语言和 Microsoft .NET 的公共语言运行时 (CLR) 之间集成的库。Lua 脚本可以使用它来实例化 CLR 对象、访问属性、调用方法,甚至使用 Lua 函数处理事件。
网站
依赖项:.NET。也适用于 Linux 上的 Mono 运行时 http://www.mono-project.com。
注意:版本 1.5.3 构建了一个可以在常规 Lua 解释器中加载的 C 模块 DLL。版本 2.0 及更高版本完全是托管代码。 [4][5][6][7][2][3]
在 LuaInterface 文档中没有提到如何实例化 .NET 数组。它只需通过用数字索引类型引用来完成
local a = SomeType[5] for i = 1,a.Length do print(i, a[i - 1]) -- .NET arrays are zero-based. end
当从 Lua 中使用 CLR 时,加载类型和类的普通方法可能看起来有点冗长
net = require "luainterface" net.load_assembly("System.Windows.Forms") net.load_assembly("System.Drawing") Form = net.import_type("System.Windows.Forms.Form") Button = net.import_type("System.Windows.Forms.Button") Point = net.import_type("System.Drawing.Point") local form1 = Form() local button1 = Button() button1.Location = Point(10, 10)
如果可以使用类似这样的语法,那就太好了
require "net" Form = net.System.Windows.Forms.Form Button = net.System.Windows.Forms.Button Point = net.System.Drawing.Point local form1 = Form() local button1 = Button() button1.Location = Point(10, 10)
可以选择将 .NET 类型显示为顶层名称
require "net" System = net.System Form = System.Windows.Forms.Form Button = System.Windows.Forms.Button Point = System.Drawing.Point local form1 = Form() local button1 = Button() button1.Location = Point(10, 10)
没有必要将每个类型名称都设置为顶层
require "net" System = net.System local form1 = System.Windows.Forms.Form() local button1 = System.Windows.Forms.Button() button1.Location = System.Drawing.Point(10, 10)
这是方法
-- Create a metatable for our name components local metatable = { [".NET"] = {getmetatable=getmetatable} } -- Load LuaInterface local g = getfenv(0) setfenv(0, metatable[".NET"]) local init, e1, e2 = loadlib("LuaInterfaceLoader.dll", "luaopen_luainterface") assert(init, (e1 or '') .. (e2 or '')) init() setfenv(0, g) -- Lookup a .NET identifier component. function metatable:__index(key) -- key is e.g. "Form" local mt = getmetatable(self) local luanet = mt[".NET"] -- Get the fully-qualified name, e.g. "System.Windows.Forms.Form" local fqn = ((self[".fqn"] and self[".fqn"] .. ".") or "") .. key -- Try to find either a luanet function or a CLR type local obj = luanet[key] or luanet.import_type(fqn) -- If key is neither a luanet function or a CLR type, then it is simply -- an identifier component. if obj == nil then -- It might be an assembly, so we load it too. luanet.load_assembly(fqn) obj = { [".fqn"] = fqn } setmetatable(obj, mt) end -- Cache this lookup self[key] = obj return obj end -- A non-type has been called; e.g. foo = System.Foo() function metatable:__call(...) error("No such type: " .. self[".fqn"], 2) end -- This is the root of the .NET namespace net = { [".fqn"] = false } setmetatable(net, metatable) -- Preload the mscorlib assembly net.load_assembly("mscorlib") return nil