GoesSoftware.SuperSDK.Lua 7.3.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package GoesSoftware.SuperSDK.Lua --version 7.3.0
                    
NuGet\Install-Package GoesSoftware.SuperSDK.Lua -Version 7.3.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="GoesSoftware.SuperSDK.Lua" Version="7.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="GoesSoftware.SuperSDK.Lua" Version="7.3.0" />
                    
Directory.Packages.props
<PackageReference Include="GoesSoftware.SuperSDK.Lua" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add GoesSoftware.SuperSDK.Lua --version 7.3.0
                    
#r "nuget: GoesSoftware.SuperSDK.Lua, 7.3.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package GoesSoftware.SuperSDK.Lua@7.3.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=GoesSoftware.SuperSDK.Lua&version=7.3.0
                    
Install as a Cake Addin
#tool nuget:?package=GoesSoftware.SuperSDK.Lua&version=7.3.0
                    
Install as a Cake Tool

SuperSDK.Lua

SuperSDK Lua 脚本桥接库,基于 MoonSharp(纯 C# Lua 5.2 解释器,无需安装任何外部运行时)。

dotnet add package GoesSoftware.SuperSDK.Lua

1. 初始化

1.1 静态门面(单例,向后兼容)

using SuperSDK.Lua;

LuaEngine.Initialize();                 // 扫描 [LuaExpose] 并注册
LuaEngine.ModulesPath = "Scripts/libs"; // 可选,require 搜索路径

Initialize() 幂等,重复调用无副作用。
LuaEngine 所有静态方法委托给内部的 LuaEngine.Default 实例。

1.2 实例模式(多运行时隔离)

当需要多个独立 Lua 运行环境时(例如每个 Fixture / Slot 一个独立引擎),直接创建 LuaRuntime 实例:

var runtime1 = new LuaRuntime();
runtime1.ModulesPath = "Scripts/libs";
runtime1.Initialize();

var runtime2 = new LuaRuntime();
runtime2.Initialize();

runtime1.Execute("x = 100");
runtime2.Execute("x = 200");

runtime1.Call<int>("x");  // → 100
runtime2.Call<int>("x");  // → 200

runtime1.Dispose();
runtime2.Dispose();

线程安全:不同 LuaRuntime 实例可安全运行在不同线程。
同一实例不能同时从多个线程调用。


2. 导出 C# 对象到 Lua

2.1 自动注入:[LuaExpose]

[LuaExpose(Name = "App")]        // 不指定 Name 则用类名
public class AppBridge
{
    public int    Add(int a, int b)  => a + b;
    public string Greet(string name) => $"Hello, {name}!";
}
// LuaRuntime.Initialize() 时自动扫描程序集,注入为 Lua 全局 App
  • 普通类:自动 new() 后注册(需无参构造函数)
  • 静态类:以 UserData.CreateStatic 注册

2.2 手动注入实例:Register<T>()

// 非泛型版(通过运行时类型推断)
runtime.Register("config", new ConfigBridge());

// 泛型版(推荐):类型注册使用声明类型 T,不受派生类影响
runtime.Register<ConfigBridge>("config", new ConfigBridge());

2.3 跨 Runtime 共享同一对象

把同一 C# 实例注入多个 LuaRuntime,它们操作的是同一块内存:

var hwService = new HardwareService(fixtureId);

foreach (var runner in slotRunners.Values)
    runner.Runtime.Register<HardwareService>("hw", hwService);
-- Lua 里任意 Slot 调用,共享同一硬件服务
hw:Open()
local data = hw:Read()

2.4 可见性规则

注册进 Lua 后,成员的可见性由 C# 访问修饰符 决定:

C# 声明 Lua 可访问?
public 方法 / 属性 / 字段
internal / private / protected

如需精确控制,使用 [MoonSharpHidden] 隐藏特定成员:

[MoonSharpUserData]
public class HardwareService
{
    public void Open()  { ... }   // ✅ Lua 可调用

    [MoonSharpHidden]
    public void InternalReset() { ... }  // ❌ Lua 不可见
}

[MoonSharpUserData] 本身不影响可见性,仅让 MoonSharp 在首次使用时自动完成类型注册,省去手动调用 UserData.RegisterType<T>()


3. 枚举注入:InjectEnum<T>()

将 C# 枚举自动注入为 Lua 全局 table,枚举值变动时 Lua 端无需任何修改:

runtime.InjectEnum<TestStatus>();
// 等效于在 Lua 执行: TestStatus = { Pass=0, Fail=1, Skip=2 }
if result == TestStatus.Pass then
    Log("test", "通过")
end

可指定自定义表名:

runtime.InjectEnum<Direction>("Dir");  // Lua: Dir = { North=0, South=1, ... }

4. 执行脚本

// 执行 Lua 代码字符串
runtime.Execute("x = 42");

// 执行 .lua 文件
runtime.ExecuteFile("Scripts/main.lua");

// 调用 Lua 全局函数
DynValue result = runtime.Call("myFunc", arg1, arg2);
int sum = runtime.Call<int>("add", 3, 4);

4.1 批量加载目录:LoadDirectory()

按自定义顺序加载目录下所有 *.lua 文件(跳过 _ 开头的文件):

runtime.LoadDirectory(
    path:           "Scripts/",
    orderFn:        f => Path.GetFileNameWithoutExtension(f) switch {
                        "Common"  => 1,   // 最先加载
                        "hook"    => 2,
                        "startup" => 99,  // 最后加载
                        _         => 50
                    },
    logTag:         "MyRunner",
    recursive:      true,
    errorFormatter: ex => ex.Message
);
参数 说明 默认值
path 扫描目录 必填
orderFn 加载顺序函数,返回整数(小的先加载),null 则字母序 null
logTag 错误日志 tag "Lua"
recursive 是否递归子目录 false
errorFormatter 异常格式化函数 ex.Message

5. 内置全局函数

初始化后自动注入,无需 require,直接在 Lua 中调用:

函数 说明
Log(tag, msg) DEBUG 日志
LogInfo(tag, msg) INFO 日志
LogWarn(tag, msg) WARNING 日志
LogError(tag, msg) ERROR 日志
Pub(msg) 发布 C# 消息对象(需先 RegisterMessage<T>
Sub(typeName, fn) 订阅 C# 消息类型(需先 RegisterMessage<T>
Now() 当前时间字符串 "HH:mm:ss.fff"
Sleep(ms) 阻塞 ms 毫秒

日志函数同时发布 LuaLogMsg,C# 可订阅:

MessageBus.Subscribe<LuaLogMsg>(this, e =>
    Console.WriteLine($"[{e.Level}] {e.LogName}: {e.Text}"));

6. 消息总线(Pub / Sub)

消息类型只在 C# 端定义,通过 RegisterMessage<T>() 暴露给 Lua。
Lua 和 C# 共享同一条 MessageBus 管道,消息双向互通。

// C# 端:定义 + 注册
public class PlayerDiedEvent
{
    public string Reason { get; set; } = "";
}

runtime.RegisterMessage<PlayerDiedEvent>();
-- Lua 端:订阅 + 发布
Sub("PlayerDiedEvent", function(msg)
    LogInfo("game", "死亡原因:" .. msg.Reason)
end)

local msg = PlayerDiedEvent()
msg.Reason = "fell into void"
Pub(msg)
// C# 端同样可以收发
MessageBus.Subscribe<PlayerDiedEvent>(this, e =>
    Console.WriteLine("Died: " + e.Reason));

MessageBus.Pub(new PlayerDiedEvent { Reason = "explosion" });
// → Lua 的 Sub 回调同样会触发

自定义发布通道(例如 Slot 隔离):

runtime.RegisterMessage<ItemTestResultMsg>(
    customPubHandler: msg => MessageBus.Pub(msg, msg.FixtureId, msg.SlotId));

7. 预加载标准库

以下库无需 require,初始化后直接可用。

7.1 json — rxi/json.lua v0.1.2(MIT)

local s = json.encode({ name = "SDK", ver = 3 })
local t = json.decode(s)
print(t.name)  -- → SDK

7.2 inspect — kikito/inspect.lua v3.1.0(MIT)

LogInfo("dbg", inspect({ 1, 2, { a = 3 } }))
-- → { 1, 2, { a = 3 } }

7.3 math.* 扩展

函数 / 常量 说明
math.clamp(x, min, max) 限定范围
math.lerp(a, b, t) 线性插值
math.round(x [, dec]) 四舍五入(AwayFromZero)
math.sign(x) -1 / 0 / 1
math.map(x, inMin, inMax, outMin, outMax) 区间映射
math.norm(x, lo, hi) 归一化 0..1
math.dist2d(x1,y1, x2,y2) 2D 距离
math.dist3d(x1,y1,z1, x2,y2,z2) 3D 距离
math.tau
math.inf 正无穷

7.4 re — .NET Regex 包装

函数 说明
re.test(str, pattern) 是否匹配 → bool
re.match(str, pattern) 首个匹配 → string 或 nil
re.matches(str, pattern) 所有匹配 → table
re.groups(str, pattern) 首个匹配的捕获组 → table
re.replace(str, pat, rep) 替换 → string
re.split(str, pattern) 分割 → table

完整 API

LuaRuntime(实例类)

每个实例拥有独立的 Script、消息处理器和全局作用域。

方法 说明
new LuaRuntime() 创建新的独立运行时
Initialize(params Assembly[]) 初始化,扫描 [LuaExpose]
Execute(string luaCode) 执行 Lua 代码字符串
ExecuteFile(string path) 执行 .lua 文件
Call(string func, params object[]) 调用 Lua 全局函数
Call<T>(string func, params object[]) 调用并转换返回值
Register(string name, object instance) 注册 C# 对象为 Lua 全局(非泛型)
Register<T>(string name, T instance) 注册 C# 对象为 Lua 全局(泛型,推荐)
InjectEnum<T>(string? tableName) 将 C# 枚举注入为 Lua 全局 table
SetGlobal(string name, object? value) 设置 Lua 全局变量(数字/字符串/bool 等)
GetGlobal(string name) 读取 Lua 全局变量
RegisterMessage<T>(luaName?, customPubHandler?) 注册消息类型,Lua 可构造/Pub/Sub
UnregisterMessage<T>() 取消注册消息类型
RegisterFunction(name, callback) 注册 C# 回调为 Lua 自由函数
LoadDirectory(path, orderFn?, logTag, recursive, errorFormatter?) 批量加载目录下 .lua 文件
AddModulesPath(string path) 添加 require 搜索目录
Reset() 重置(清空所有状态,可重新初始化)
Dispose() 释放资源(调用 Reset)
Script 底层 MoonSharp Script 实例
ModulesPath require 搜索路径(Initialize 前设置)

LuaEngine(静态门面)

所有方法委托给 LuaEngine.DefaultLuaRuntime 实例),向后完全兼容。

方法 说明
Default 获取共享的 LuaRuntime 实例
Initialize(params Assembly[]) 初始化引擎,扫描 [LuaExpose]
Execute / ExecuteFile / Call / Call<T> 同 LuaRuntime
Register / Register<T> 同 LuaRuntime
InjectEnum<T> 同 LuaRuntime
SetGlobal / GetGlobal 同 LuaRuntime
RegisterMessage<T> / UnregisterMessage<T> 同 LuaRuntime
RegisterFunction 同 LuaRuntime
LoadDirectory 同 LuaRuntime
AddModulesPath 同 LuaRuntime
Reset() 重置并释放 Default 实例
Script 底层 MoonSharp Script 实例

SuperSDK Lua 脚本桥接库,基于 MoonSharp(纯 C# Lua 5.2 解释器,无需安装任何外部运行时)。

dotnet add package GoesSoftware.SuperSDK.Lua

1. 初始化

1.1 静态门面(单例,向后兼容)

using SuperSDK.Lua;

LuaEngine.Initialize();                          // 扫描 [LuaExpose] 并注册
LuaEngine.ModulesPath = "Scripts/libs";           // 可选,require 搜索路径

Initialize() 幂等,重复调用无副作用。
LuaEngine 所有静态方法委托给内部的 LuaEngine.Default 实例。

1.2 实例模式(多运行时隔离)

当需要多个独立 Lua 运行环境时(例如每个 Fixture 一个独立引擎),直接创建 LuaRuntime 实例:

using SuperSDK.Lua;

// 每个实例拥有独立的 Script、Pub/Sub 处理器和全局变量
var runtime1 = new LuaRuntime();
runtime1.ModulesPath = "Scripts/libs";
runtime1.Initialize();

var runtime2 = new LuaRuntime();
runtime2.Initialize();

// 各自执行不会互相影响
runtime1.Execute("x = 100");
runtime2.Execute("x = 200");

runtime1.Call<int>("x");  // → 100
runtime2.Call<int>("x");  // → 200

// 用完释放
runtime1.Dispose();
runtime2.Dispose();

线程安全:不同 LuaRuntime 实例可以安全地运行在不同线程上。
同一实例不能同时从多个线程调用。


2. 导出 C# 对象到 Lua

[LuaExpose(Name = "App")]       // Lua 中 App.XXX 访问,不指定 Name 则用类名
public class AppBridge
{
    public int    Add(int a, int b)   => a + b;
    public string Greet(string name)  => $"Hello, {name}!";
}
  • 普通类:自动 new() 后注册(需无参构造函数)
  • 静态类:以 UserData.CreateStatic 注册
  • 手动注册(静态门面):LuaEngine.Register("MyObj", instance)
  • 手动注册(实例):runtime.Register("MyObj", instance)

3. 执行脚本

// ── 静态门面 ─────────────────────────────────────
var result = LuaEngine.Execute("return App.Add(3, 4)");
LuaEngine.ExecuteFile("Scripts/main.lua");
int sum = LuaEngine.Call<int>("add", 3, 4);

// ── 实例模式 ─────────────────────────────────────
var rt = new LuaRuntime();
rt.Initialize();
rt.ExecuteFile("Scripts/main.lua");
int sum2 = rt.Call<int>("add", 3, 4);

4. 内置全局函数

初始化后自动注入,无需 require,直接在 Lua 中调用:

函数 说明
Log(tag, msg) DEBUG 日志
LogInfo(tag, msg) INFO 日志
LogWarn(tag, msg) WARNING 日志
LogError(tag, msg) ERROR 日志
Pub(msg) 发布 C# 消息对象(需先 RegisterMessage<T>
Sub(typeName, fn) 订阅 C# 消息类型(需先 RegisterMessage<T>
Now() 当前时间 "HH:mm:ss.fff"
Sleep(ms) 阻塞 ms 毫秒

日志函数同时发布 LuaLogMsg,C# 可订阅:

MessageBus.Subscribe<LuaLogMsg>(this, e =>
    Console.WriteLine($"[{e.Level}] {e.LogName}: {e.Text}"));

5. 消息总线(Pub / Sub)

消息类型只在 C# 端定义,通过 RegisterMessage<T>() 暴露给 Lua。
Lua 和 C# 共享同一条 MessageBus 管道,消息双向互通。

// ── C# 端:定义 + 注册 ───────────────────────────
public class PlayerDiedEvent
{
    public string Reason { get; set; } = "";
}

LuaEngine.RegisterMessage<PlayerDiedEvent>();
-- ── Lua 端:订阅 + 发布 ──────────────────────────
Sub("PlayerDiedEvent", function(msg)
    LogInfo("game", "死亡原因:" .. msg.Reason)
end)

local msg = PlayerDiedEvent()
msg.Reason = "fell into void"
Pub(msg)
// ── C# 端同样可以收发 ────────────────────────────
MessageBus.Subscribe<PlayerDiedEvent>(this, e =>
    Console.WriteLine("Died: " + e.Reason));

MessageBus.Pub(new PlayerDiedEvent { Reason = "explosion" });
// → Lua 的 Sub 回调同样会触发

6. 预加载标准库

以下库无需 require,初始化后直接可用(嵌入资源随 NuGet 包发布)。

6.1 json — rxi/json.lua v0.1.2(MIT)

local s = json.encode({ name = "SDK", ver = 3 })
local t = json.decode(s)
print(t.name)   -- → SDK

6.2 inspect — kikito/inspect.lua v3.1.0(MIT)

LogInfo("dbg", inspect({ 1, 2, { a = 3 } }))
-- → { 1, 2, { a = 3 } }

6.3 math.* 扩展

函数 / 常量 说明
math.clamp(x, min, max) 限定范围
math.lerp(a, b, t) 线性插值
math.round(x [, dec]) 四舍五入
math.sign(x) -1 / 0 / 1
math.map(x, inMin, inMax, outMin, outMax) 区间映射
math.norm(x, lo, hi) 归一化 0..1
math.dist2d(x1,y1, x2,y2) 2D 距离
math.dist3d(x1,y1,z1, x2,y2,z2) 3D 距离
math.tau
math.inf 正无穷

6.4 re — .NET Regex 包装

函数 说明
re.test(str, pattern) 是否匹配 → bool
re.match(str, pattern) 首个匹配 → string 或 nil
re.matches(str, pattern) 所有匹配 → table
re.groups(str, pattern) 首个匹配的捕获组 → table
re.replace(str, pat, rep) 替换 → string
re.split(str, pattern) 分割 → table

完整 API

LuaEngine(静态门面)

所有方法委托给 LuaEngine.DefaultLuaRuntime 实例),向后完全兼容。

方法 说明
Default 获取共享的 LuaRuntime 实例
Initialize(params Assembly[]) 初始化引擎,扫描 [LuaExpose]
Execute(string luaCode) 执行 Lua 字符串
ExecuteFile(string path) 执行 .lua 文件
Call(string func, params object[]) 调用 Lua 全局函数
Call<T>(string func, params object[]) 调用并转换返回值
Register(string name, object instance) 注册 C# 对象为 Lua 全局
SetGlobal(string name, object? value) 设置 Lua 全局变量
GetGlobal(string name) 读取 Lua 全局变量
RegisterMessage<T>(luaName?) 注册消息类型,Lua 可构造/Pub/Sub
UnregisterMessage<T>() 取消注册消息类型
RegisterFunction(name, callback) 注册 C# 回调为 Lua 函数
AddModulesPath(string path) 添加 require 搜索目录
Reset() 重置引擎(销毁并释放 Default 实例)
Script 底层 MoonSharp Script 实例

LuaRuntime(实例类)

每个实例拥有独立的 Script、消息处理器和全局作用域。

方法 说明
new LuaRuntime() 创建新的独立运行时
Initialize(params Assembly[]) 初始化,扫描 [LuaExpose]
Execute(string luaCode) 执行 Lua 字符串
ExecuteFile(string path) 执行 .lua 文件
Call(string func, params object[]) 调用 Lua 全局函数
Call<T>(string func, params object[]) 调用并转换返回值
Register(string name, object instance) 注册 C# 对象为 Lua 全局
SetGlobal(string name, object? value) 设置 Lua 全局变量
GetGlobal(string name) 读取 Lua 全局变量
RegisterMessage<T>(luaName?) 注册消息类型
UnregisterMessage<T>() 取消注册消息类型
RegisterFunction(name, callback) 注册 C# 回调为 Lua 函数
AddModulesPath(string path) 添加 require 搜索目录
Reset() 重置(清空所有状态,可重新初始化)
Dispose() 释放资源(调用 Reset + 标记已释放)
Script 底层 MoonSharp Script 实例
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
7.14.0 0 4/10/2026
7.13.0 0 4/10/2026
7.12.0 0 4/10/2026
7.11.0 21 4/10/2026
7.10.0 46 4/8/2026
7.9.0 77 4/7/2026
7.8.0 84 4/4/2026
7.7.0 89 4/4/2026
7.6.0 80 4/4/2026
7.5.0 79 4/4/2026
7.4.0 85 4/4/2026
7.3.0 80 4/4/2026
7.2.0 81 4/3/2026
7.1.0 82 4/3/2026
7.0.0 77 4/1/2026
6.6.2 104 3/31/2026
6.6.0 80 3/31/2026
6.5.2 80 3/31/2026
6.5.0 86 3/31/2026
6.4.0 80 3/30/2026
Loading failed

更新 DriverBridge