Skip to content

Commit 39cf747

Browse files
authored
chore: Improve docs (#205)
* Add more information to docs * add information on world containers * add edit url to mdbook
1 parent bc83c5a commit 39cf747

File tree

6 files changed

+155
-3
lines changed

6 files changed

+155
-3
lines changed

crates/bevy_mod_scripting_core/src/lib.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,19 +126,34 @@ impl<P: IntoScriptPluginParams> Plugin for ScriptingPlugin<P> {
126126

127127
impl<P: IntoScriptPluginParams> ScriptingPlugin<P> {
128128
/// Adds a context initializer to the plugin
129+
///
130+
/// Initializers will be run every time a context is loaded or re-loaded
129131
pub fn add_context_initializer(&mut self, initializer: ContextInitializer<P>) -> &mut Self {
130132
self.context_initializers.push(initializer);
131133
self
132134
}
133135

134-
/// Adds a context pre-handling initializer to the plugin
136+
/// Adds a context pre-handling initializer to the plugin.
137+
///
138+
/// Initializers will be run every time before handling events.
135139
pub fn add_context_pre_handling_initializer(
136140
&mut self,
137141
initializer: ContextPreHandlingInitializer<P>,
138142
) -> &mut Self {
139143
self.context_pre_handling_initializers.push(initializer);
140144
self
141145
}
146+
147+
/// Adds a runtime initializer to the plugin.
148+
///
149+
/// Initializers will be run after the runtime is created, but before any contexts are loaded.
150+
pub fn add_runtime_initializer(&mut self, initializer: RuntimeInitializer<P>) -> &mut Self {
151+
self.runtime_settings
152+
.get_or_insert_with(Default::default)
153+
.initializers
154+
.push(initializer);
155+
self
156+
}
142157
}
143158

144159
// One of registration of things that need to be done only once per app

docs/book.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ description = "Documentation for the Bevy Scripting library"
99
[output.html]
1010
additional-js = ["multi-code-block.js"]
1111
git-repository-url = "https://github.com/makspll/bevy_mod_scripting"
12+
edit-url-template = "https://github.com/makspll/bevy_mod_scripting/edit/main/{path}"

docs/src/Development/AddingLanguages/evaluating-feasibility.md

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,44 @@
22

33
In order for a language to work well with BMS it's necessary it supports the following features:
44
- [ ] Interoperability with Rust. If you can't call it from Rust easilly and there is no existing crate that can do it for you, it's a no-go.
5-
- [ ] First class functions. Or at least the ability to call an arbitrary function with an arbitrary number of arguments from a script. Without this feature, you would need to separately generate code for the bevy bindings. This is painful and goes against the grain of the project.
5+
- [ ] First class functions. Or at least the ability to call an arbitrary function with an arbitrary number of arguments from a script. Without this feature, you would need to separately generate code for the bevy bindings which is painful and goes against the grain of BMS.
66

77
## First Classs Functions
88

9+
They don't necessarily have to be first class from the script POV, but they need to be first class from the POV of the host language. This means that the host language needs to be able to call a function with an arbitrary number of arguments.
10+
11+
### Examples
12+
13+
Let's say your language supports a `Value` type which can be returned to the script. And it has a `Value::Function` variant. The type on the Rust side would look something like this:
14+
15+
```rust,ignore
16+
pub enum Value {
17+
Function(Arc<Fn(&[Value]) -> Value>),
18+
// other variants
19+
}
20+
```
21+
22+
This is fine, and can be integrated with BMS. Since an Fn function can be a closure capturing a `DynamicScriptFunction`. If there is no support for `FnMut` closures though, you might face issues in the implementation. Iterators in `bevy_mod_scripting_functions` for example use `DynamicScriptFunctionMut` which cannot work with `Fn` closures.
23+
24+
Now let's imagine instead another language with a similar enum, supports this type instead:
25+
26+
```rust
27+
pub enum Value {
28+
Function(Arc<dyn Function>),
29+
// other variants
30+
}
31+
32+
pub trait Function {
33+
fn call(&self, args: Vec<Value>) -> Value;
34+
35+
fn num_params() -> usize;
36+
}
37+
```
38+
39+
This implies that to call this function, you need to be able to know the amount of arguments it expects at COMPILE time. This is not compatibile with dynamic functions, and would require a lot of code generation to make work with BMS.
40+
Languages with no support for dynamic functions are not compatible with BMS.
41+
42+
## Interoperability with Rust
43+
44+
Not all languages can easilly be called from Rust. Lua has a wonderful crate which works out the ffi and safety issues for us. But not all languages have this luxury. If you can't call it from Rust easilly and there is no existing crate that can do it for you, integrating with BMS might not be the best idea.
45+
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Necessary Features
2+
3+
In order for a language to be called "implemented" in BMS, it needs to support the following features:
4+
5+
- Every script function which is registered on a type's namespace must:
6+
- Be callable on a `ReflectReference` representing object of that type in the script
7+
```lua
8+
local my_reference = ...
9+
my_reference:my_Registered_function()
10+
```
11+
- If it's static it must be callable from a global proxy object for that type, i.e.
12+
```lua
13+
MyType.my_static_function()
14+
```
15+
- `ReflectReferences` must support a set of basic features:
16+
- Access to fields via reflection i.e.:
17+
```lua
18+
local my_reference = ...
19+
my_reference.my_field = 5
20+
print(my_reference.my_field)
21+
```
22+
- Basic operators and standard operations are overloaded with the appropriate standard dynamic function registered:
23+
- Addition: dispatches to the `add` binary function on the type
24+
- Multiplication: dispatches to the `mul` binary function on the type
25+
- Division: dispatches to the `div` binary function on the type
26+
- Subtraction: dispatches to the `sub` binary function on the type
27+
- Modulo: dispatches to the `rem` binary function on the type
28+
- Negation: dispatches to the `neg` unary function on the type
29+
- Exponentiation: dispatches to the `pow` binary function on the type
30+
- Equality: dispatches to the `eq` binary function on the type
31+
- Less than: dispatches to the `lt` binary function on the type
32+
- Length: calls the `len` method on `ReflectReference` or on the table if the value is one.
33+
- Iteration: dispatches to the `iter` method on `ReflectReference` which returns an iterator function, this can be repeatedly called until it returns `ScriptValue::Unit` to signal the end of the iteration.
34+
- Print: calls the `display_ref` method on `ReflectReference` or on the table if the value is one.
35+
- Script handlers, loaders etc. must be implemented such that the `ThreadWorldContainer` is set for every interaction with script contexts, or anywhere else it might be needed.
36+

docs/src/SUMMARY.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
- [Managing Scripts](./Summary/managing-scripts.md)
88
- [Running Scripts](./Summary/running-scripts.md)
99
- [Controlling Script Bindings](./Summary/controlling-script-bindings.md)
10+
- [Modifying Script Contexts](./Summary/customizing-script-contexts.md)
1011

1112
# Scripting Reference
1213

@@ -24,4 +25,5 @@
2425
- [Introduction](./Development/introduction.md)
2526
- [Setup](./Development/setup.md)
2627
- [New Languages](./Development/AddingLanguages/introduction.md)
27-
- [Evaluating Feasibility](./Development/AddingLanguages/evaluating-feasibility.md)
28+
- [Evaluating Feasibility](./Development/AddingLanguages/evaluating-feasibility.md)
29+
- [Necessary Features](./Development/AddingLanguages/necessary-features.md)
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Modifying Script Contexts
2+
3+
You should be able to achieve what you need by registering script functions in most cases. However sometimes you might want to override the way contexts are loaded, or how the runtime is initialized.
4+
5+
This is possible using `Context Initializers` and `Context Pre Handling Initializers` as well as `Runtime Initializers`.
6+
7+
8+
## Context Initializers
9+
10+
For example, let's say you want to set a dynamic amount of globals in your script, depending on some setting in your app.
11+
12+
You could do this by customizing the scripting plugin:
13+
```rust,ignore
14+
let plugin = LuaScriptingPlugin::default();
15+
plugin.add_context_initializer(|script_id: &str, context: &mut Lua| {
16+
let globals = context.globals();
17+
for i in 0..10 {
18+
globals.set(i, i);
19+
}
20+
Ok(())
21+
});
22+
23+
app.add_plugins(plugin)
24+
```
25+
26+
The above will run every time the script is loaded or re-loaded.
27+
28+
## Context Pre Handling Initializers
29+
30+
If you want to customize your context before every time it's about to handle events, you can use `Context Pre Handling Initializers`:
31+
```rust,ignore
32+
let plugin = LuaScriptingPlugin::default();
33+
plugin.add_context_pre_handling_initializer(|script_id: &str, entity: Entity, context: &mut Lua| {
34+
let globals = context.globals();
35+
globals.set("script_name", script_id.to_owned());
36+
Ok(())
37+
});
38+
```
39+
## Runtime Initializers
40+
41+
Some scripting languages, have the concept of a `runtime`. This is a global object which is shared between all contexts. You can customize this object using `Runtime Initializers`:
42+
```rust,ignore
43+
let plugin = SomeScriptingPlugin::default();
44+
plugin.add_runtime_initializer(|runtime: &mut Runtime| {
45+
runtime.set_max_stack_size(1000);
46+
Ok(())
47+
});
48+
```
49+
50+
## Accessing the World in Initializers
51+
52+
You can access the world in these initializers by using the thread local: `ThreadWorldContainer`:
53+
```rust,ignore
54+
55+
let plugin = LuaScriptingPlugin::default();
56+
plugin.add_context_initializer(|script_id: &str, context: &mut Lua| {
57+
let world = ThreadWorldContainer::get_world();
58+
world.with_resource::<MyResource>(|res| println!("My resource: {:?}", res));
59+
Ok(())
60+
});
61+
```

0 commit comments

Comments
 (0)