Controlling Script Bindings
A binding is anything a script can access to communicate with your Rust code, i.e. binding script code to rust code. Bindings are written once in Rust, and work in every supported language.
Functions are registered on a type or a namespace, see where functions can live. Scripts reach them through namespaces.
Dynamic Functions
Everything callable by scripts must first be registered in the dynamic function registry. Notably we do not make use of the normal bevy function registry to improve performance and usability. This means you cannot call just any function.
In order for a function to be callable by a script it must adhere to a few requirements:
- Each argument must implement
FromScript. - Each return type must implement
IntoScript. - Each argument must also implement
GetTypeDependencies - Each return type must also implement
GetTypeDependencies
The into/from requirements allow us to convert these types to ScriptValue’s, and each supported scripting language can then marshall these into the script.
These traits are implemented for primitives, but if you want to interact with one of your Reflect implementing types, you will need to use one of R<T>, M<T> or V<T> wrappers in place of &T, &mut T and T respectively.
These wrappers enable us to safely interact with bevy, and claim any necessary mutex’es on Resources, Components or Allocations.
The GetTypeDependencies, trait is simply a local trait alias for GetTypeRegistration with less strict type requirements. It allows us to register all the types necessary for the function calls, so that you don’t have to register anything manually. If your type implements GetTypeRegistration you should not face any issues on this front.
Registering Script Functions
Registering functions can be done via the NamespaceBuilder like below:
NamespaceBuilder::<ReflectReference>::new(&mut world)
.register(
"hello_world",
|_self: ReflectReference, s: String| {
println!("{s}")
},
);
NamespaceBuilder::in_namespace(&mut world, "my_game")
.register(
"hello_world2",
|s: String| {
println!("{s}")
},
);
This will allow you to call this function within Lua like so:
some_value:hello_world("hi from method!")
import_namespace("my_game").hello_world2("hi from my_game!")
new also registers the type in the type registry. Functions on ReflectReference are available on every value, and receive it as their first argument, see where functions can live.
Macros
The above is a bit tedious, so instead you can use the script_bindings macro, which applies to impl blocks like so:
#[script_bindings(name = "test_fn")]
impl TestStruct {
/// My docs !!
///
/// Arguments:
/// * `_self` - the first argument
/// * `arg1` - the second argument
/// Returns:
/// * `return` - nothing
fn test_fn(_self: R<TestStruct>, mut arg1: usize) {}
}
pub fn main() {
let mut app = App::new();
register_test_fn(app.world_mut())
}
Note the documentation will automatically be picked up and stored for the purposes of reflection and documentation generation, including argument/return type specific docs.
Deriving FromScript and IntoScript
Generally all reflect types are wrapped in: R<T> V<T> or M<T> when writing script bindings. However some types may opt in to implement FromScript or IntoScript directly.
Doing this requires implementing a set of other traits which tell the runtime how to manage your type in conversion and function dispatch.
The most trivial way to allow your type to be used directly in bindings is to apply derive macros like so:
#![allow(unused)]
fn main() {
#[derive(Reflect, ScriptType)]
pub struct MyThing(usize);
#[script_bindings]
impl MyThing {
// Can now be used directly without V<> wrapper, acts exactly like V<MyThing>
pub fn test(thing: MyThing) -> MyThing {
thing
}
}
}
ScriptType implements FromScript, IntoScript, ArgMeta, GetTypeDependencies and TypedThrough at once, converting through V<Self>.
If you wish to customize one of the conversions, write that impl by hand and use #[script_type(from = custom)] or #[script_type(into = custom)]. This skips the generated impl and documents the type as opaque in generated docs. See the custom conversions example for more information.
Context Arguments
Each script function call always receives an additional context argument: FunctionCallContext.
You can opt-in to receive this argument in your own function definitions by adding it as the first argument.
The context contains requests from the caller to your function, such as “I am calling you from a 1-indexed array system, please convert the index first”, This argument is only relevant if you’re targeting multiple languages.
It also allows you to retrieve the world via FunctionCallContext::world().
You can use this as follows:
NamespaceBuilder::<ReflectReference>::new(&mut world)
.register(
"hello_world",
|ctx: FunctionCallContext, _self: ReflectReference, s: String| {
let world = ctx.world()?;
let should_use_0_indexing = ctx.convert_to_0_indexed();
println!("{should_use_0_indexing} {s}");
Ok(())
},
);
Dynamic Arguments
To accept any kind of value, i.e. numbers or strings alike, take ScriptValue arguments:
NamespaceBuilder::<ReflectReference>::new(&mut world)
.register(
"is_integer",
|s: ScriptValue| {
match s {
ScriptValue::Integer(i) => true,
_ => false
}
},
);
You can treat return values similarly. To accept a reference of any type while keeping it typed in the docs, see Generics. To accept callbacks, names or tables of options, see Typed arguments.
Typed arguments
These wrappers and derives keep the exact type of arguments which aren’t reflected values, in the book and the Lua language server files:
/// Spawns an enemy
#[derive(ScriptData)]
#[script_data(namespace = "game")]
struct SpawnOptions {
name: String,
speed: Option<Speed>, // optional
on_death: Option<FunctionOf<fn(V<Entity>) -> ()>>,
}
#[derive(ScriptData)]
#[script_data(namespace = "game")]
enum Speed {
Named(ByName<Pace>), // "Slow" | "Fast", for `enum Pace { Slow, Fast }`
Exact(f32), // 2.5
}
#[script_bindings(remote, namespace = "game")]
impl NamespaceMembers {
fn spawn(ctxt: FunctionCallContext, options: SpawnOptions) -> Result<V<Entity>, InteropError> { .. }
}
game.spawn({ name = "goblin", speed = "Fast", on_death = function(entity) end }) -- `entity` is an ecs.Entity
game.spawn({ name = "goblin", sped = 2 }) -- flagged by the language server, an error at runtime
| scripts pass | documented as | |
|---|---|---|
FunctionOf<fn(A, B) -> R> | a function, which is a DynamicScriptFunction in Rust | fun(arg1: A, arg2: B): R |
ByName<E> | a unit variant of the reflected enum E by its name as in Rust, or a reference to an E | "Slow" | "Fast" |
#[derive(ScriptData)] struct | a map of its fields: a table in Lua, an object in Rune | the class of its fields, a data type in the book |
#[derive(ScriptData)] enum | the value of any variant, each holding one value: the first variant whose type converts it | an alias of the union of the variants’ types (game.Speed), a data type in the book |
ScriptData is plain data, copied across: a struct is read from the map when passed and written to a new map when returned, so changing one doesn’t change the other. Use it for what crosses once (options, properties, events, results). Use a reflected type for what scripts hold a handle to, or Rust keeps as state. A type is one or the other: deriving both Reflect and ScriptData doesn’t compile.
Each field converts like a function argument of its type. A missing field takes its type’s default, so Option<T> fields can be left out. Unknown fields, missing fields without a default and mistyped fields are errors naming the field.
An enum’s variants are tried in order, so put the more specific of two types taking the same kind of value first, i.e. ByName before String.
Unions only try the types which could convert a value, as told by FromScript::could_convert. When implementing FromScript by hand, override it to rule out the kinds of values your type never converts.
Generics
Reflection only knows concrete types (Handle<Image>, Time<Virtual>), so generic signatures and types use markers standing for their parameters: A, B and C, from bevy_mod_scripting::bindings::function::generics. Markers only change the documentation and the Lua language server files, the values are references at runtime.
Note
The markers are real types:
Ais a reflected unit struct implementingAsset,Default,Cloneand the other traits generic parameters are usually bounded by, soHandle<A>andTime<A>are real types too. AHandle<Image>is not aHandle<A>, soV<Handle<A>>, which copies the value out, can’t receive one. UseValueOf<Handle<A>>. See theAAPI docs.
Generic functions
Two wrappers carry the markers in signatures:
ValueOf<T, R>: a value converted asR, aReflectReferenceunless given, documented as aT.TypeOf<R, A>: a type argument passed asR, i.e. a registration, documented as the parameterA.
Using the same marker ties them together, so get_component returns a value of the type it is given:
fn get_component(
ctxt: FunctionCallContext,
entity: V<Entity>,
registration: TypeOf<V<ScriptComponentRegistration>, A>,
) -> Result<Option<ValueOf<A>>, InteropError>
local bms = import_namespace("bms")
local Transform = import_namespace("transform").Transform
local transform = bms.world.get_component(assert(bms.current_entity()), Transform) -- typed as a Transform
print(transform)
A marker can also stand inside a type, i.e. ValueOf<Handle<A>> accepts the handle of any asset type, see References.
For values which aren’t references, give the conversion: ValueOf<A, ScriptValue> takes any value, typed as whatever the script passed:
// with `MyBox` declared as a generic type (see below): `boxed(5)` is a `MyBox<integer>`
fn boxed(initial: ValueOf<A, ScriptValue>) -> V<MyBox<A>> { .. }
Generic types
Instantiations of a generic type would be documented as unrelated types. Declare the generic type from your plugin, instantiated with markers, with its namespace, parameter names and docs:
use bevy_mod_scripting::bindings::function::generics::{A, GenericTypesAppExt};
app.register_generic_type::<Time<A>>("time", &["T"], "A clock, i.e. `Time<Virtual>`.");
Fields of type A are then documented as being of the parameter T, and instantiations as Time<T> applied to their arguments. Further parameters use B and C (Hashed<A, B>). A parameter with bounds the markers don’t satisfy gets a marker of its own:
bevy_mod_scripting::bindings::generic_marker! {
/// Stands for the material of `MyMaterialHolder<M>`
pub struct M;
}
impl MyMaterial for M {}
app.register_type::<M>()
.register_generic_type::<MyMaterialHolder<M>>("my_crate", &["M"], "...");
Fallible functions
Your script functions can return errors either by:
- Returning
Result<T: IntoScript, InteropError> - Returning
ScriptValueand manually creating theScriptValue::Error(into_interop_error.into())variant.
Reserved Functions
There are a few reserved functions that you can override by registering them on a specific type:
| Function Name | Description | Overridable? | Has Default Implementation? |
|---|---|---|---|
| get | a getter function, used for indexing into a type | no | yes |
| set | a setter function, used for setting a value on a type | no | yes |
| sub | a subtraction function, used for subtracting two values | yes | no |
| add | an addition function, used for adding two values | yes | no |
| mul | a multiplication function, used for multiplying two values | yes | no |
| div | a division function, used for dividing two values | yes | no |
| rem | a remainder function, used for getting the remainder of two values | yes | no |
| neg | a negation function, used for negating a value | yes | no |
| pow | a power function, used for raising a value to a power | yes | no |
| rsub, rdiv, rrem, rpow | the reflected sub, div, rem and pow, called on the right operand when the left one is not a value, i.e. 1 - v calls rsub(v, 1). add and mul are called with their operands swapped instead | yes | no |
| eq | an equality function, used for checking if two values are equal | yes | no |
| lt | a less than function, used for checking if a value is less than another | yes | no |
| iter | an iterator function, used for iterating over a value | no | yes |
| display | a display function, used for pretty printing values | no* | yes |
| debug | a display function, used for displaying the internals of a value | no* | yes |
* - You can register an instance of ReflectDisplayWithTypeInfo type data on Reflect implementing types to override their printing behavior
In this context overridable indicates whether language implementations will look for a specific function on your type before looking at the generic ReflectReference namespace. You can still remove the existing registration for these functions on the ReflectReference namespace if you want to replace them with your own implementation.
Note the ReflectReference namespace is special, in that functions defined on it, act like a fallback and hence apply to ALL references.
Where functions can live
The type in the impl block you apply script_bindings to (or the one passed to NamespaceBuilder) decides where the functions are available:
impl target | Available on | Receives |
|---|---|---|
MyType | MyType values and the MyType type, as imported from its namespace | whatever you declare |
ReflectReference | every value, after MyType’s own functions | the value |
StaticTypeRef | every type, after MyType’s own functions | the type, filled in automatically |
NamespaceMembers | the namespace given by namespace = "..." (or NamespaceBuilder::in_namespace), i.e. import_namespace("my_game") | whatever you declare |
When the same name exists in more than one place, the most specific one wins.
These types are defined by BMS, so script_bindings blocks on ReflectReference, StaticTypeRef or NamespaceMembers in your crate need the remote attribute.
Functions available on every type
The StaticTypeRef namespace is the equivalent for types, i.e. Vec3 in Vec3.new(..).
Functions registered on it are available on every type, and receive the type as their first argument, which is filled in automatically:
NamespaceBuilder::<StaticTypeRef>::new(app.world_mut()).register(
"describe",
|ctxt: FunctionCallContext, type_ref: V<StaticTypeRef>| -> Result<String, InteropError> {
Ok(type_ref.type_info(&ctxt.world()?)?.type_path().to_string())
},
);
local Vec3 = import_namespace("math").Vec3
print(Vec3.describe()) -- "glam::Vec3"
A function registered on the type itself always takes priority over one on StaticTypeRef.
The new constructor is implemented this way, see Constructing Arbitrary Types.
Types scripts don’t make or use this way, such as handles the runtime gives out, opt out with #[reflect(NoTypeFunctions)] (ReflectNoTypeFunctions): only their own functions remain, in scripts and in the generated docs.
Signatures which depend on the type
A shared function’s signature can refer to the type it is bound to, using the placeholder types BoundValue (a value of the type), BoundFields (a table of the type’s fields) and BoundHandle (a handle to an asset of the type).
Wherever the function is bound to a type, these are replaced with the type, so the documentation and the Lua language server files show, for example, MyStruct.new(payload: MyStruct.Fields): MyStruct rather than a generic table and reference, or Image.load(path: string): Handle<Image>.
Functions using BoundHandle are only documented on asset types, i.e. types registered with register_asset_reflect.
The same placeholders work for functions on EnumVariantRef, which are bound to each variant of each enum when the LAD file is built (as functions in the Variant namespace). Placeholders left unbound are documented as what they are at runtime, a ReflectReference and a table.
The enum variants of a type are also available on the type, i.e. MyEnum.Variant, after the functions.
Namespace members
Each type registered with the type registry is an entry in the table import_namespace returns for its namespace, i.e. import_namespace("math").Vec3.
Functions which don’t belong to a type are members of a namespace, declared on impl NamespaceMembers:
#[script_bindings(remote, namespace = "my_game")]
impl NamespaceMembers {
fn spawn_enemy(health: f32) { /* ... */ }
}
local my_game = import_namespace("my_game")
my_game.spawn_enemy(5.0)
Values are registered per namespace with AppScriptNamespaceMembers::register_value, and are made each time the namespace is imported.
The only globals are the builtins: import_namespace, export_namespace and register_callback. world is in the bms namespace: import_namespace("bms").world.
Types are not globals, which keeps types with the same name from shadowing each other. Use the filter of CoreScriptGlobalsPlugin to choose which types scripts can look up by name.