Skip to main content

Crate rhue

Crate rhue 

Source
Expand description

§Rhue

Luau-flavoured scripting you can embed in Rust.

use rhue::{Engine, Value};

let mut engine = Engine::new();
engine.set_global("name", "Aalto");
let values = engine.eval(r#"
    local function counter()
        local n = 0
        return function() n += 1 return n end
    end
    local next = counter()
    next() next()
    return next(), "hello, " .. name
"#).unwrap();
assert_eq!(values, [Value::Number(3.0), Value::from("hello, Aalto")]);

let err = engine.eval_expr("1 + true").unwrap_err();
assert_eq!(err.to_string(), "attempt to perform arithmetic (add) on boolean");

§Calling Rust from scripts, and scripts from Rust

use rhue::{Context, Engine, Function, Variadic};

let mut engine = Engine::new();
// parameters and results convert on their own, a wrong type is a
// script error ("invalid argument #1 to 'add' (number expected, got string)").
engine.register("add", |a: f64, b: f64| a + b);
engine.register("sum", |xs: Variadic<f64>| xs.iter().sum::<f64>());
// returning Err raises an error in the script
engine.register("half", |n: i64| -> Result<i64, String> {
    if n % 2 == 0 { Ok(n / 2) } else { Err(format!("{n} is odd")) }
});
// take `&mut Context` first to call back into scripts
engine.register("twice", |cx: &mut Context, f: Function, x: f64| -> Result<f64, rhue::ScriptError> {
    let once: f64 = cx.call(&f, x)?;
    cx.call(&f, once)
});

assert_eq!(engine.eval_as::<f64>("return add(1, 2) + sum(1, 2, 3)").unwrap(), 9.0);
assert_eq!(engine.eval_as::<f64>("return twice(function(x) return x * 3 end, 2)").unwrap(), 18.0);

engine.eval("function greet(who) return 'hi ' .. who end").unwrap();
let greeting: String = engine.call_global("greet", "Zae").unwrap();
assert_eq!(greeting, "hi Zae");

Rust types turn into script objects with UserData (usually derived).

§Types

Scripts opt into Luau-style type checking with --!strict (or --!nonstrict). Registered functions get declared with types from their Rust signatures, and a chunk with type errors doesn’t run.

use rhue::{Engine, ErrorKind};

let mut engine = Engine::new();
engine.register("add", |a: f64, b: f64| a + b);
assert_eq!(engine.global_type("add").unwrap(), "(number, number) -> number");

let err = engine.eval("--!strict\nlocal n: number = add(1, 'two')").unwrap_err();
assert_eq!(err.kind, ErrorKind::Type);
assert_eq!(err.to_string(), "Type '\"two\"' could not be converted into 'number'");

let n: f64 = engine.eval_as("--!strict\nlocal function sq(x: number): number return x * x end return sq(add(1, 2))").unwrap();
assert_eq!(n, 9.0);

§Running untrusted scripts

An engine can cap how many instructions a call can run and how much memory scripts can hold. Going over either is a normal error and the engine’s still usable after. Each script can get its own globals too.

use rhue::Engine;

let mut engine = Engine::new();
engine.set_instruction_limit(Some(100_000));
engine.set_memory_limit(Some(1 << 20));

let err = engine.eval("while true do end").unwrap_err();
assert!(err.to_string().contains("instruction limit"));
let err = engine.eval("local t = {} for i = 1, 1e7 do t[i] = i end").unwrap_err();
assert!(err.to_string().contains("memory"));

// plugins in separate environments can't see each other's globals
let a = engine.create_environment();
let b = engine.create_environment();
engine.eval_in(&a, "secret = 42").unwrap();
assert_eq!(engine.eval_in(&b, "return secret").unwrap(), [rhue::Value::Nil]);

§Modules and compiled chunks

require finds modules the host gives it, from source or compiled ahead of time. Compiled chunks load without parsing or type-checking, go through the bytecode verifier, and keep their types.

use rhue::Engine;

let mut engine = Engine::new();
engine.add_module("geometry", "--!strict
    local M = {}
    function M.area(w: number, h: number): number return w * h end
    return M");
let bytes = engine.compile_to_bytes("stats", "return { mean = function(a, b) return (a + b) / 2 end }").unwrap();
engine.add_module_bytes("stats", &bytes).unwrap();

let n: f64 = engine.eval_as("return require('geometry').area(3, 4) + require('stats').mean(2, 4)").unwrap();
assert_eq!(n, 15.0);

// the module's types reach scripts that require it
assert!(engine.check("main.rhue", "--!strict\nlocal s: string = require('geometry').area(1, 2)").is_err());

§Scripts that wait

Engine::spawn runs a script as a task the host resumes, and Engine::open_tasks adds Luau’s task library, driven by a clock the host moves forward with Engine::step.

use rhue::{Engine, TaskState, Value};

let mut engine = Engine::new();
engine.open_tasks();
let mut task = engine.spawn("door", "
    local opened = coroutine.yield('waiting for a key')
    task.wait(1.5)
    return 'opened with ' .. opened
").unwrap();
assert_eq!(task.state(), TaskState::Suspended(vec![Value::from("waiting for a key")]));

engine.resume(&mut task, vec![Value::from("brass key")]).unwrap();
assert!(!task.is_finished()); // now in task.wait
engine.step(1.0);
assert!(!task.is_finished());
engine.step(1.0);
assert_eq!(task.state(), TaskState::Finished(vec![Value::from("opened with brass key")]));

Modules§

serde
Converting between Rhue values and Rust types with serde (the serde feature).

Structs§

Analysis
What editor tooling learns about a chunk (see Engine::analyze).
AnyUserData
A handle to a userdata object of any type. AnyUserData::downcast turns it into a typed Ud<T>.
ArgError
Argument index (1-based) had the wrong type.
Args
The arguments (or results) being converted, in order.
Buffer
A handle to a buffer (buffer.create) inside an engine, a fixed-size mutable array of bytes. Read and write it through a Context.
Chunk
A compiled script, from Engine::compile or Engine::load. Run it with Engine::run as many times as you want, cloning one is cheap.
CompileOptions
Context
A view of an engine’s VM. Call functions, read and write tables and globals, make userdata.
ConversionError
A value had the wrong type for the Rust side.
Debugger
What a debug hook can look at, the stack of the paused script.
Diagnostic
One error or warning, before it’s rendered.
Engine
The entry point for embedding Rhue.
Environment
A separate set of globals (see the module docs). Cheap to clone, and clones share the same globals.
Error
An error from compiling or running a script. It keeps a copy of the source its spans point into, so it can render itself with Error::render and can be sent across threads.
Exports
What a module file exports, for navigating across modules.
FieldUse
A field read from a local or a module (m.name, m:name()), for navigating across modules.
Function
A handle to a function (script or native) inside an engine. Call it with Engine::call or Context::call.
HeapStats
Memory statistics; see Engine::heap_stats. Live object counts and memory use, for collectgarbage("count") and crate::Vm::heap_stats.
HookMask
Which events the hook wants.
InlayHint
A type shown after a name or a parameter list.
InterruptHandle
Stops a script from another task or thread. Cheap to clone, and it’s Send + Sync.
Outline
A file’s outline; see outline.
Reloaded
What a reload did (see Engine::reload_module).
ScriptError
An error raised by a script, a native, or a conversion.
SemanticToken
A highlighted range of source, for semantic highlighting.
SourceFile
A named chunk of source text. Every prototype compiled from it holds an Rc to it, so a runtime error always renders against the right file, even when a function from one eval gets called from another.
Span
A half-open byte range start..end into some source.
StackFrame
One frame of the stack.
Symbol
A named thing defined in a file, for outlines and workspace symbols.
Table
A handle to a table inside an engine. Read and write it through a Context (engine.context(), or the one a native receives).
Task
A script or function running as a coroutine (see Engine::spawn).
Thread
A handle to a coroutine inside an engine. Make one with Context::create_thread and run it with Context::resume, or get one from a script.
TypeBuilder
Adds methods, properties and static functions to userdata type T.
Ud
A typed handle to a userdata object. Clones share the object, so changes made through one (or by scripts) show up in all of them.
Variadic
Any number of values of one type. As a parameter it takes all the remaining arguments, as a result it returns several values (not a table).
WithContext
Marks natives whose first parameter is &mut Context.

Enums§

Base
What a field is read from.
DebugEvent
What the hook is told about.
ErrorKind
Which phase an Error came from.
HintKind
What an InlayHint describes.
Severity
SymbolKind
What kind of thing a Symbol is.
TaskState
Where a Task stopped.
TokenKind
What a SemanticToken is.
TypeMode
How hard a chunk gets type-checked, set by a directive comment at the top of the file.
Value
A Rhue value, owned and independent of the VM’s heap.

Traits§

FromArg
Something that takes its value(s) from an argument list. Any FromValue takes one (nil if missing), Variadic takes the rest.
FromValue
Script → Rust, for one value.
FromValues
Script values → a Rust argument or result list.
IntoAsyncNative
An async Rust function that can be registered with Engine::register_async. Parameters work like IntoNative, and it returns a future whose output is IntoNativeResult. The future doesn’t borrow the engine, so it takes its arguments by value (async move).
IntoMethod
A Rust function usable as a method of T: Fn(&mut T, args...), or Fn(&mut Context, &mut T, args...). See TypeBuilder::method.
IntoNative
A Rust function that can be registered as a script function: a closure or fn whose parameters are FromArg (any FromValue type, or a trailing Variadic) and whose result is IntoNativeResult. It can take &mut Context first to call back into scripts. Marker just tells the impls apart, it’s always inferred.
IntoNativeResult
What a native can return: any IntoValues (a value, (), a tuple, a Variadic), or a Result of one whose error converts into ScriptError (String and &str do).
IntoValue
Rust → script, for one value.
IntoValues
Rust values → a script argument or result list.
UserData
A Rust type scripts can use. Usually derived:

Functions§

is_chunk
Whether bytes start like a saved chunk.
is_module_name
Whether name is a module name that module_paths keeps inside its folder: parts split by ., none of them empty, and nothing that a path would treat specially (/, \\, :).
module_paths
Where require(name) looks for a module under dir, in order: a.b is dir/a/b.rhue, then dir/a/b/init.rhue. The CLI, the language server and the debugger all find modules this way, so a loader that uses it agrees with them. It only builds the paths, nothing gets read.
outline
The outline of source (see Outline). A file that doesn’t parse or resolve only gets its lexical tokens.

Derive Macros§

UserData