Skip to content

Cookbook

Liu.Yandong.Hanks edited this page Aug 19, 2026 · 3 revisions

示例手册

Cookbook

适用版本:4.0.0

Applies to 4.0.0.

首页 · 语言指南 · 宿主集成

这里收录可直接改造的小型方案。每个示例只展示一件事;完整 API 语义请回到对象页面确认。

This page collects small patterns that can be adapted directly. Each example demonstrates one concern; return to the object page for complete API semantics.

从内存加载模块

适合测试、规则编辑器或不希望将脚本落盘的场景。

Use this for tests, rule editors, or cases where scripts should not be written to disk.

var resolver = ScriptSources.Memory("mem://rules/")
    .Add("main.as", """
        @module(RULES);
        export func score(value) { return value * 2; }
        """);

var options = EngineOptions.Default.WithCompiler(c =>
{
    c.SourceResolver = resolver;
    c.Mode = CompilationMode.Dynamic;
});

var engine = new AuroraEngine(options);
await engine.BuildAsync("main.as");
using var domain = engine.CreateDomain();
var score = domain.Execute("RULES", "score", ScriptDatum.FromNumber(21));

传递宿主状态

把每次运行独有的数据放入 ScriptObject,脚本通过 $state 读取。不要把每个请求的数据写进 Engine 级全局原型。

Put per-run data in a ScriptObject and read it through $state. Do not write per-request data into the engine-level global prototype.

var state = new ScriptObject();
state.Define("Tenant", "acme");
using var domain = engine.CreateDomain(userState: state);
@module(MAIN);

export func tenantMessage() {
    return "hello " + $state.Tenant;
}

组合模块

让每个模块只导出明确的函数或常量,使用相对路径导入。路径的最终解析由 Source Resolver 决定。

Let each module export explicit functions or constants and import by relative path. Final path resolution is controlled by the Source Resolver.

// lib/format.as
@module(FORMAT);

export func label(name) {
    return "[" + name.trim() + "]";
}
// main.as
@module(MAIN);
import format from "./lib/format";

export func run(name) {
    return format.label(name);
}

安全地处理 JSON

只对可信且格式正确的文本调用 JSON.parse。输入不合法时先在宿主边界返回错误,或者在脚本中捕获并转换为项目约定的错误结果。

Call JSON.parse only on trusted, well-formed text. For invalid input, return an error at the host boundary or catch and translate it to the project's agreed error result.

func readEnabled(text) {
    var config = JSON.parse(text);
    return Boolean(config.enabled);
}

return readEnabled('{"enabled":true}');

构造长文本

循环中使用 StringBuffer,最后一次性读取文本。

Use StringBuffer in a loop and read the text once at the end.

var buffer = new StringBuffer();
for (var i = 0; i < 3; i++) {
    buffer.appendLine("item=" + i);
}
return buffer.toString();

执行前检查

在自动生成、热更新或用户编辑脚本的流程中,先调用编译检查,再创建或替换运行 Domain。MCP 客户端可以使用 aurora_check_scriptaurora_check_file 完成同样的预检。

In generated, hot-patched, or user-edited script flows, compile-check first and only then create or replace a running domain. MCP clients can use aurora_check_script or aurora_check_file for the same preflight.

await engine.BuildAsync("main.as");
using var domain = engine.CreateDomain();
var result = domain.Execute("MAIN", "run");

Clone this wiki locally