NLua 文档

发布于:2025-03-19 ⋅ 阅读:(14) ⋅ 点赞:(0)

目录

入门指南

使用 .Net 对象

沙盒机制

Unity 集成

Unity 使用注意事项


github 地址:

https://github.com/NLua/NLua

入门指南

NLua 允许在 UWP、Windows、Linux、Mac、iOS、Android 上使用 C# 中的 Lua。

public class SomeClass
{
    public string MyProperty { get; private set; }

    public SomeClass(string param1 = "defaulValue")
    {
        MyProperty = param1;
    }

    public int Func1()
    {
        return 32;
    }

    public string AnotherFunc(int val1, string val2)
    {
        return "Some String";
    }

    public static string StaticMethod(int param)
    {
        return "Return of Static Method";
    }
}

Using UTF-8 Encoding:

NLua 运行在 KeraLua 绑定层之上,默认情况下它使用 ASCII 编码来处理字符串。如果你希望使用 UTF-8 编码,只需将 Lua.State.Encoding 属性设置为 Encoding.UTF8 即可:


using (Lua lua = new Lua())
{
	lua.State.Encoding = Encoding.UTF8;
	lua.DoString("res = 'Файл'");
	string res = (string)lua["res"];

	Assert.AreEqual("Файл", res);
}

创建 Lua 状态:

using NLua;
	
Lua state = new Lua ()

计算简单表达式:

// Lua can return multiple values, for this reason DoString return a array of objects
// Lua 可以返回多个值,因此 DoString 返回一个对象数组
var res = state.DoString ("return 10 + 3*(5 + 2)")[0] as double;

将原始值传递给 state:

double val = 12.0;
state ["x"] = val; // Create a global value 'x' 
var res = (double)state.DoString ("return 10 + x*(5 + 2)")[0];

获取全局变量:

state.DoString ("y = 10 + x*(5 + 2)");
double y = (double) state ["y"]; // Retrieve the value of y 检索y的值

获取 Lua 函数:

state.DoString (@"
function ScriptFunc (val1, val2)
	if val1 > val2 then
		return val1 + 1
	else
		return val2 - 1
	end
end
");
var scriptFunc = state ["ScriptFunc"] as LuaFunction;
// LuaFunction.Call will also return a array of objects, since a Lua function
// can return multiple values
//Lua函数,调用将返回一个对象数组,因为Lua函数可以返回多个值
var res = (int)scriptFunc.Call (3, 5).First();

使用 .Net 对象

向 state 传递 .Net 对象:

SomeClass obj = new SomeClass ("Param");
// Create a global value 'obj' of .NET type SomeClass 
//创建的 .net SomeClass类 global 值 “obj” 
state ["obj"] = obj; 
// This could be any .NET object, from BCL or from your assemblies
//这可能是任何 .net 对象,来自 BCL 或者程序集

在 Lua 中使用 .NET 程序集:

要访问任何 .NET 库以在 Lua 中创建对象、事件等,需要让 NLua 将 CLR 作为 Lua 包加载。只需调用 LoadCLRPackage 方法,并在您的 Lua 脚本中使用 import 函数加载程序集。例如:

state.LoadCLRPackage ();
state.DoString (@" import ('MyAssembly', 'MyNamespace') 
		   import ('System.Web') ");
// import will load any .NET assembly and they will be available inside the Lua context.
// import 将会加载任何 .NET 程序集,并且它们将在 Lua 上下文中可用。

创建 .NET 对象: 只需使用类名后跟 ( ) 来创建对象。

state.DoString (@"
	--you can suppress default values.可省略默认值
	obj2 = SomeClass() 
	client = WebClient()
");

调用实例方法: 要调用实例方法,需要使用 : 符号。可以从传递到 Lua 或在 Lua 上下文内创建的对象上调用方法。

state.DoString (@"
local res1 = obj:Func1()
local res2 = obj2:AnotherFunc (10, 'hello')
local res3 = client:DownloadString('http://nlua.org')
");

调用静态方法: 您可以直接通过类名和 . 符号从 Lua 中调用静态方法。

state.DoString (@"
local res4 = SomeClass.StaticMethod(4)
");

访问属性: 从 Lua 使用 . 符号即可获取(或设置)任何属性。

state.DoString (@"
local res5 = obj.MyProperty
");

所有方法、事件或属性都必须是公共可用的,NLua 不会调用非公开成员。

如果您使用 Xamarin.iOS,需要对要在 NLua 中使用的类应用 [Preserve] 特性,否则链接器会在最终二进制文件中删除未使用的类。

沙盒机制

有许多方法可以在应用程序内部为脚本建立沙箱。强烈推荐您使用纯 Lua 来实现沙箱。您可以重写 import 函数,确保在用户脚本执行前不加载 .NET 程序集。

state.DoString (@"
	import = function () end
");

链接:

lua-users wiki: Sand Boxes

Unity 集成

1. 为 .NET 2.0 构建或从 NuGet 下载 KeraLua 和 NLua(使用下载包链接)

2. 如果选择下载:将文件扩展名从 .nupkg 更改为 .zip

3. 在 Unity 项目的 Assets 目录中创建文件夹 Plugins/KeraLuaPlugins/NLua

4. 将这些 zip 文件中的 netstandard2.0 内容解压到新创建的 Unity 文件夹中。您的目录结构应大致如下(KeraLua 的运行时根据您的构建目标进行定制):

Plugins
├── KeraLua
│   ├── LICENSE
│   ├── LICENSE.meta
│   ├── lib
│   │   ├── netstandard2.0
│   │   │   ├── KeraLua.dll
│   │   │   ├── KeraLua.dll.meta
│   │   │   ├── KeraLua.xml
│   │   │   └── KeraLua.xml.meta
│   │   └── netstandard2.0.meta
│   ├── lib.meta
│   ├── runtimes
│   │   ├── linux-x64
│   │   │   ├── native
│   │   │   │   ├── liblua54.so
│   │   │   │   └── liblua54.so.meta
│   │   │   └── native.meta
│   │   ├── linux-x64.meta
│   │   ├── osx
│   │   │   ├── native
│   │   │   │   ├── liblua54.dylib
│   │   │   │   └── liblua54.dylib.meta
│   │   │   └── native.meta
│   │   ├── osx.meta
│   │   ├── win-x64
│   │   │   ├── native
│   │   │   │   ├── lua54.dll
│   │   │   │   └── lua54.dll.meta
│   │   │   └── native.meta
│   │   ├── win-x64.meta
│   │   ├── win-x86
│   │   │   ├── native
│   │   │   │   ├── lua54.dll
│   │   │   │   └── lua54.dll.meta
│   │   │   └── native.meta
│   │   └── win-x86.meta
│   └── runtimes.meta
├── KeraLua.meta
├── NLua
│   ├── LICENSE
│   ├── LICENSE.meta
│   ├── lib
│   │   ├── netstandard2.0
│   │   │   ├── NLua.dll
│   │   │   └── NLua.dll.meta
│   │   └── netstandard2.0.meta
│   └── lib.meta
└── NLua.meta

5. 在 Unity 检查器中逐个查看 KeraLua 运行时的 liblua54文件,并根据文件夹为编辑器和独立平台设置正确的平台设置。别忘了应用更改。

Unity 使用注意事项

•  你可能会想要将路径追加到 `package.path` 中,你可以通过类似这样的方式来实现:

lua.DoString("package.path = package.path .. \";" + Application.persistentDataPath + "/?/?.lua;" + Application.persistentDataPath + "/?.lua\"");

•  你将需要将 `Debug.Log` 暴露给 Lua(并重写 `print` 函数以便查看 Lua 的日志输出)。

•  从 Lua 返回的数字将以 `double` 类型呈现。

•  在 Lua 实例上设置的字段可能为 `null`,你需要妥善处理这种情况。

end