lua

2.1k 词

LuaInterface 库

LuaInterface下载地址

  • LuaInterface是一个用于在Lua语言和Microsoft .NET平台的公共语言运行时(CLR)之间集成的库。 Lua脚本可以使用它来实例化CLR对象,访问属性,调用方法,甚至使用Lua函数处理事件。
  • LuaInterface.Lua类是CLR访问Lua解释器的主要接口,一个LuaInterface.Lua类对象就代表了一个Lua解释器(或Lua执行环境),Lua解释器可以同时存在多个,并且它们之间是完全相互独立的。

示例

在 C# 中调用 Lua

1
2
3
4
5
6
7
8
9
10
11

MyMath = {}

MyMath.Name = "MyMath"
MyMath.PI = 3.1415

function (first, second)
return first+second
end

return MyMath
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Program.cs
using System;
using LuaInterface;

class Program {
static void Main(string[] args) {
// 创建 Lua 解释器
Lua lua = new Lua();

// 执行 Lua 语句
lua.DoString("print('Lua in C#')");

lua.DoString(@"
for i=1, 5, 1 do
print(i);
end
");

// 执行 Lua 文件,参数为 Lua 文件所在路径,下面 MyMath.lua 文件放在项目输出目录中
lua.DoFile("MyMath.lua");

// 使用 Lua 文件中的变量
Console.WriteLine(lua.GetString("MyMath.Name"));
Console.WriteLine(lua.GetNumber("MyMath.PI"));

// 使用 Lua 文件中的函数
LuaFunction Add = lua.GetFunction("MyMath.Add");
Console.WriteLine(Add.Call(1, 2)[0]);

Console.ReadLine();
}
}
1
2
3
4
5
6
7
8
9
Lua in C#
1
2
3
4
5
MyMath
3.1415
3

在 Lua 中调用 C

测试项目名称:CSharpAndLua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Tools.cs
using System;

namespace CSharpAndLuaTest {
class Tools {

public static void Show() {
Console.WriteLine("Show something ... ");
}

public void Print() {
Console.WriteLine("This is member method.");
}
}
}
1
2
3
4
5
6
7
8
9
-- Main.lua
require("luanet") -- 引用 luanet 程序集
luanet.load_assembly("CSharpAndLua") -- 加载程序集
Tools = luanet.import_type("CSharpAndLuaTest.Tools"); -- 引用类型

Tools.Show(); -- 调用静态方法

myTools = Tools()
myTools:Print() -- 调用成员方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Program.cs
using System;
using LuaInterface;

namespace CSharpAndLua {
class Program {
static void Main(string[] args) {
// 创建 Lua 解释器
Lua lua = new Lua();
lua.DoFile("Main.lua");

Console.ReadLine();
}
}
}
1
2
Show something ...
This is member method.

热更新初尝试

  1. 打开项目程序集所在的根目录bin
  2. 更改Lua脚本代码内容
  3. 运行程序集

修改 lua 文件

1
2
3
4
5
6
7
8
9
10
11
-- Main.lua
require("luanet") -- 引用 luanet 程序集
luanet.load_assembly("CSharpAndLua") -- 加载程序集
Tools = luanet.import_type("CSharpAndLuaTest.Tools"); -- 引用类型

Tools.Show(); -- 调用静态方法

myTools = Tools()
myTools:Print() -- 调用成员方法

print("Update this file.")

1
2
3
Show something ...
This is member method.
Update this file.