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(theserdefeature).
Structs§
- Analysis
- What editor tooling learns about a chunk (see
Engine::analyze). - AnyUser
Data - A handle to a userdata object of any type.
AnyUserData::downcastturns it into a typedUd<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 aContext. - Chunk
- A compiled script, from
Engine::compileorEngine::load. Run it withEngine::runas many times as you want, cloning one is cheap. - Compile
Options - Context
- A view of an engine’s VM. Call functions, read and write tables and globals, make userdata.
- Conversion
Error - 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::renderand can be sent across threads. - Exports
- What a module file exports, for navigating across modules.
- Field
Use - 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::callorContext::call. - Heap
Stats - Memory statistics; see
Engine::heap_stats. Live object counts and memory use, forcollectgarbage("count")andcrate::Vm::heap_stats. - Hook
Mask - Which events the hook wants.
- Inlay
Hint - A type shown after a name or a parameter list.
- Interrupt
Handle - 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). - Script
Error - An error raised by a script, a native, or a conversion.
- Semantic
Token - A highlighted range of source, for semantic highlighting.
- Source
File - A named chunk of source text. Every prototype compiled from it holds an
Rcto it, so a runtime error always renders against the right file, even when a function from oneevalgets called from another. - Span
- A half-open byte range
start..endinto some source. - Stack
Frame - 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_threadand run it withContext::resume, or get one from a script. - Type
Builder - 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).
- With
Context - Marks natives whose first parameter is
&mut Context.
Enums§
- Base
- What a field is read from.
- Debug
Event - What the hook is told about.
- Error
Kind - Which phase an
Errorcame from. - Hint
Kind - What an
InlayHintdescribes. - Severity
- Symbol
Kind - What kind of thing a
Symbolis. - Task
State - Where a
Taskstopped. - Token
Kind - What a
SemanticTokenis. - Type
Mode - 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
FromValuetakes one (nilif missing),Variadictakes the rest. - From
Value - Script → Rust, for one value.
- From
Values - Script values → a Rust argument or result list.
- Into
Async Native - An async Rust function that can be registered with
Engine::register_async. Parameters work likeIntoNative, and it returns a future whose output isIntoNativeResult. The future doesn’t borrow the engine, so it takes its arguments by value (async move). - Into
Method - A Rust function usable as a method of
T:Fn(&mut T, args...), orFn(&mut Context, &mut T, args...). SeeTypeBuilder::method. - Into
Native - A Rust function that can be registered as a script function: a closure or
fnwhose parameters areFromArg(anyFromValuetype, or a trailingVariadic) and whose result isIntoNativeResult. It can take&mut Contextfirst to call back into scripts.Markerjust tells the impls apart, it’s always inferred. - Into
Native Result - What a native can return: any
IntoValues(a value,(), a tuple, aVariadic), or aResultof one whose error converts intoScriptError(Stringand&strdo). - Into
Value - Rust → script, for one value.
- Into
Values - Rust values → a script argument or result list.
- User
Data - A Rust type scripts can use. Usually derived:
Functions§
- is_
chunk - Whether
bytesstart like a saved chunk. - is_
module_ name - Whether
nameis a module name thatmodule_pathskeeps 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 underdir, in order:a.bisdir/a/b.rhue, thendir/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(seeOutline). A file that doesn’t parse or resolve only gets its lexical tokens.