Skip to main content
基于 FluxonRuntime.java 的登记手册,帮助你在宿主启动时向脚本注入函数、变量或扩展。

适用场景

  • 暴露宿主能力(文件/网络/游戏对象等)给脚本。
  • 设置函数的线程模型(异步或主线程)。
  • 在不改核心源码的情况下增量添加命名空间或扩展函数。

单例访问

FluxonRuntime runtime = FluxonRuntime.getInstance();
  • newEnvironment():创建新的解释器环境(自动 bake 缓存)。
  • getSystemFunctions() / getExtensionFunctions() / getSystemVariables():调试或导出当前注册表。
  • setPrimaryThreadExecutor(Executor executor):替换主线程执行器,供主线程函数使用。

函数注册

方法用途
registerFunction(name, signature, callable)注册同步函数。
registerFunction(namespace, name, signature, callable)带命名空间的函数,例如 fs:crypto
registerAsyncFunction(name, signature, callable)异步函数,Function#isAsync()true
registerPrimarySyncFunction(name, signature, callable)主线程函数,isPrimarySync = true
registerVariable(name, value)注入全局变量,可在脚本中直接访问。
每次注册都会设置脏标记,下一次 newEnvironment() 时自动重建缓存数组。

FunctionSignature 构建

使用 FunctionSignature 定义函数的返回类型和参数类型:
import static org.tabooproject.fluxon.runtime.FunctionSignature.returns;
import org.tabooproject.fluxon.runtime.Type;

// 返回 int,接收两个 int 参数
returns(Type.I).params(Type.I, Type.I)

// 返回 Object,无参数
returns(Type.OBJECT).noParams()

// 返回 void,接收一个 String 参数
returns(Type.VOID).params(Type.STRING)

// 简写形式
FunctionSignature.returnsObject().params(Type.OBJECT)
FunctionSignature.returnsVoid().noParams()

Type 常量参考

常量对应类型
Type.VOIDvoid
Type.OBJECTObject
Type.STRINGString
Type.Iint
Type.Jlong
Type.Ffloat
Type.Ddouble
Type.Zboolean
Type.NUMBERNumber
Type.LISTList
Type.MAPMap
Type.FILEFile
Type.PATHPath

扩展函数(target::method()

Builder 链式注册

import static org.tabooproject.fluxon.runtime.FunctionSignature.returns;
import org.tabooproject.fluxon.runtime.Type;

runtime.registerExtension(File.class, "fs:io")
       .function("exists", returns(Type.Z).noParams(), ctx -> {
           ctx.setReturnBool(ctx.getTarget().exists());
       })
       .asyncFunction("length", returns(Type.J).noParams(), ctx -> {
           ctx.setReturnLong(ctx.getTarget().length());
       })
       .syncFunction("getName", returns(Type.STRING).noParams(), ctx -> {
           ctx.setReturnRef(ctx.getTarget().getName());
       });

Builder 方法说明

方法说明
function(name, signature, callable)同步扩展。
asyncFunction(name, signature, callable)异步扩展。
syncFunction(name, signature, callable)主线程同步扩展。
扩展函数同样参与 fluxon-functions.json 导出,供 IDE/文档消费。

变量与全局对象

  • 运行时默认注册了 g(),返回 GlobalObject.INSTANCE,便于上下文调用(如 g() :: someExtension(...))。
  • 其他全局对象可通过 Environment#getRootVariables() 验证。

调试与导出

  • 直接打印 runtime.getSystemFunctions() / getExtensionFunctions() 查看注册结果。
  • 使用 ./gradlew :core:dumpFluxonCatalog 导出最新函数目录,保持 VS Code 补全与文档同步。

相关链接