bevy_mod_scripting_luars 0.2.0

A luars backend for bevy_mod_scripting with WASM support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]

use std::{
    any::TypeId,
    ops::{Deref, DerefMut},
    str,
    sync::Arc,
};

use bevy_app::{App, Plugin};
use bevy_asset::Handle;
use bevy_ecs::{
    entity::Entity,
    world::{Mut, World, WorldId},
};
use bevy_log::trace;
use bevy_mod_scripting_asset::{Language, ScriptAsset};
use bevy_mod_scripting_bindings::{
    InteropError, PartialReflectExt, WorldExtensions, function::namespace::Namespace,
    globals::AppScriptGlobalsRegistry, script_value::ScriptValue,
};
use bevy_mod_scripting_core::{
    IntoScriptPluginParams, ScriptingPlugin,
    callbacks::ScriptCallbacks,
    config::{GetPluginThreadConfig, ScriptingPluginConfiguration},
    event::CallbackLabel,
    make_plugin_config_static,
    script::ContextPolicy,
};
use bevy_mod_scripting_script::ScriptAttachment;
use bevy_mod_scripting_world::ThreadWorldContainer;
use luars::{Lua, LuaApi, LuaError, LuaFunction, LuaResult, SafeOption, Stdlib};

mod reference;
mod script_value;

/// The [luars](https://docs.rs/luars) crate this backend embeds.
///
/// Import `LuaApi`, `LuaError`, and friends from here instead of taking a
/// direct `luars` dependency.
pub use luars;
pub use reference::{LuaReflectReference, LuaStaticReflectReference};
pub use script_value::{LuaScriptValue, MultiLuaScriptValue};

make_plugin_config_static!(LuarsScriptingPlugin);

/// Per-script Lua 5.5 VM, stored as BMS's language context.
///
/// Most apps never construct this. Add [`LuarsScriptingPlugin`] and talk to
/// scripts through BMS (`ScriptComponent`, callback events, registered
/// functions). Reach for this type when you need the raw VM — a REPL, an extra
/// `set_global`, a one-off `load`.
///
/// Get a loaded context from `ScriptContexts<LuarsScriptingPlugin>`, then
/// dereference to [`luars::Lua`].
///
/// ```ignore
/// fn eval(contexts: Res<ScriptContexts<LuarsScriptingPlugin>>) {
///     let inner = contexts.read();
///     let Some((_, ctx)) = inner.first_resident_from_each_context().next() else {
///         return;
///     };
///     let Some(arc) = ctx.as_loaded() else {
///         return;
///     };
///     let mut lua = arc.lock();
///     let n: i64 = lua.load("return 1 + 2").eval().unwrap();
/// }
/// ```
pub struct LuarsContext {
    lua: Lua,
}

impl Deref for LuarsContext {
    type Target = Lua;
    fn deref(&self) -> &Self::Target {
        &self.lua
    }
}

impl DerefMut for LuarsContext {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.lua
    }
}

impl LuarsContext {
    fn new() -> Result<Self, InteropError> {
        let mut lua = Lua::new(SafeOption::default());
        open_host_stdlibs(&mut lua).map_err(|e| lua_to_interop(&mut lua, e))?;
        Ok(Self { lua })
    }

    /// Turn a luars [`LuaResult`] into a BMS [`InteropError`] using this VM's
    /// stored error message.
    pub fn map_lua<T>(&mut self, result: LuaResult<T>) -> Result<T, InteropError> {
        result.map_err(|e| lua_to_interop(&mut self.lua, e))
    }
}

fn lua_to_interop(lua: &mut Lua, e: LuaError) -> InteropError {
    InteropError::external(lua.get_error_message(e))
}

fn open_host_stdlibs(lua: &mut Lua) -> LuaResult<()> {
    #[cfg(target_arch = "wasm32")]
    {
        lua.open_stdlibs(&[
            Stdlib::Basic,
            Stdlib::Math,
            Stdlib::String,
            Stdlib::Table,
            Stdlib::Utf8,
            Stdlib::Coroutine,
            Stdlib::Package,
            Stdlib::Debug,
        ])
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        lua.open_stdlib(Stdlib::All)
    }
}

impl IntoScriptPluginParams for LuarsScriptingPlugin {
    type C = LuarsContext;
    type R = ();
    const LANGUAGE: Language = Language::Lua;

    fn build_runtime() -> Self::R {}

    fn handler() -> bevy_mod_scripting_core::handler::HandlerFn<Self> {
        luars_handler
    }

    fn context_loader() -> bevy_mod_scripting_core::context::ContextLoadFn<Self> {
        luars_context_load
    }

    fn context_reloader() -> bevy_mod_scripting_core::context::ContextReloadFn<Self> {
        luars_context_reload
    }
}

impl AsMut<ScriptingPlugin<Self>> for LuarsScriptingPlugin {
    fn as_mut(&mut self) -> &mut ScriptingPlugin<LuarsScriptingPlugin> {
        &mut self.scripting_plugin
    }
}

/// BMS language plugin that runs Lua 5.5 via [luars] instead of mlua.
///
/// Add this next to `BMSPlugin`. Leave BMS's `lua` / `lua54` features off so
/// you do not load two Lua VMs.
///
/// ```ignore
/// use bevy::prelude::*;
/// use bevy_mod_scripting::BMSPlugin;
/// use bevy_mod_scripting_luars::LuarsScriptingPlugin;
///
/// App::new()
///     .add_plugins((BMSPlugin, LuarsScriptingPlugin::default()))
///     .run();
/// ```
///
/// After that, treat this like any other BMS language: load `.lua` / `.luau`
/// assets and attach them with `ScriptComponent`.
///
/// # What scripts see
///
/// Each context gets
/// - `world`, a static handle to Bevy's [`World`];
/// - `entity`, the entity the script is attached to, when there is one;
/// - `script_asset`, the [`Handle<ScriptAsset>`] for this script;
/// - `register_callback(name, fn)`, subscribe a Lua function to a BMS callback; and
/// - every global and global-namespace function from the BMS registries.
///
/// Configure with [`bevy_mod_scripting_core::ConfigureScriptPlugin`]
/// (`set_context_policy`, `add_context_initializer`, and so on).
///
/// [luars]: https://docs.rs/luars
pub struct LuarsScriptingPlugin {
    /// Inner BMS plugin. Prefer `ConfigureScriptPlugin` helpers when you can.
    pub scripting_plugin: ScriptingPlugin<Self>,
}

fn register_plugin_globals(context: &mut LuarsContext) -> Result<(), InteropError> {
    let register = context
        .lua
        .global_state_mut()
        .create_closure(|state| {
            let callback: String = state
                .get_arg_as(1)?
                .ok_or_else(|| state.error("register_callback expects a name".to_owned()))?;
            let func: LuaFunction = state
                .get_arg_as(2)?
                .ok_or_else(|| state.error("register_callback expects a function".to_owned()))?;

            let thread_ctxt = ThreadWorldContainer
                .try_get_context()
                .map_err(|e| state.error(format!("{e:?}")))?;
            let world = thread_ctxt.world;
            let attachment = world.current_attachment().0.ok_or_else(|| {
                state.error(
                    "Cannot register callback, missing script attachment context.".to_owned(),
                )
            })?;

            world
                .with_resource_mut(|res: Mut<ScriptCallbacks<LuarsScriptingPlugin>>| {
                    let mut callbacks = res.callbacks.write();
                    callbacks.insert(
                        (attachment.clone(), callback),
                        Arc::new(
                            move |args: Vec<ScriptValue>,
                                  lua: &mut LuarsContext,
                                  world_id: WorldId| {
                                let pre_handling_callbacks =
                                    LuarsScriptingPlugin::readonly_configuration(world_id)
                                        .pre_handling_callbacks;
                                pre_handling_callbacks
                                    .iter()
                                    .try_for_each(|init| init(&attachment, lua))?;

                                let mapped: Vec<LuaScriptValue> =
                                    args.into_iter().map(LuaScriptValue).collect();
                                func.call::<_, crate::script_value::MultiLuaScriptValue>(mapped)
                                    .map_err(|e| lua_to_interop(&mut lua.lua, e))
                                    .map(
                                        crate::script_value::MultiLuaScriptValue::into_script_value,
                                    )
                            },
                        ),
                    );
                })
                .map_err(|e| state.error(e.to_string()))?;
            Ok(0)
        })
        .map_err(|e| lua_to_interop(&mut context.lua, e))?;
    context
        .lua
        .set_global("register_callback", register)
        .map_err(|e| lua_to_interop(&mut context.lua, e))?;
    Ok(())
}

impl Default for LuarsScriptingPlugin {
    fn default() -> Self {
        LuarsScriptingPlugin {
            scripting_plugin: ScriptingPlugin {
                runtime_initializers: Vec::default(),
                supported_extensions: vec!["lua", "luau"],
                context_initializers: vec![
                    |_script_id, context| {
                        context
                            .lua
                            .set_global("world", LuaStaticReflectReference(TypeId::of::<World>()))
                            .map_err(|e| lua_to_interop(&mut context.lua, e))?;
                        register_plugin_globals(context)?;
                        Ok(())
                    },
                    |_script_id, context| {
                        let world = ThreadWorldContainer.try_get_context()?.world;
                        let globals_registry =
                            world.with_resource(|r: &AppScriptGlobalsRegistry| r.clone())?;
                        let globals_registry = globals_registry.read();

                        for (key, global) in globals_registry.iter() {
                            match &global.maker {
                                Some(maker) => {
                                    let global = (maker)(world.clone())?;
                                    context
                                        .lua
                                        .set_global(
                                            key.to_string().as_str(),
                                            LuaScriptValue::from(global),
                                        )
                                        .map_err(|e| lua_to_interop(&mut context.lua, e))?;
                                }
                                None => {
                                    let ref_ = LuaStaticReflectReference(global.type_id);
                                    context
                                        .lua
                                        .set_global(key.to_string().as_str(), ref_)
                                        .map_err(|e| lua_to_interop(&mut context.lua, e))?;
                                }
                            }
                        }

                        let script_function_registry = world.script_function_registry();
                        let script_function_registry = script_function_registry.read();

                        for (key, function) in script_function_registry
                            .iter_all()
                            .filter(|(k, _)| k.namespace == Namespace::Global)
                        {
                            context
                                .lua
                                .set_global(
                                    key.name.to_string().as_str(),
                                    LuaScriptValue::from(ScriptValue::Function(function.clone())),
                                )
                                .map_err(|e| lua_to_interop(&mut context.lua, e))?;
                        }

                        Ok(())
                    },
                ],
                context_pre_handling_initializers: vec![|context_key, context| {
                    let world = ThreadWorldContainer.try_get_context()?.world;
                    if let Some(entity) = context_key.entity() {
                        context
                            .lua
                            .set_global(
                                "entity",
                                LuaReflectReference(<Entity>::allocate(
                                    Box::new(entity),
                                    world.clone(),
                                )),
                            )
                            .map_err(|e| lua_to_interop(&mut context.lua, e))?;
                    }
                    context
                        .lua
                        .set_global(
                            "script_asset",
                            LuaReflectReference(<Handle<ScriptAsset>>::allocate(
                                Box::new(context_key.script()),
                                world,
                            )),
                        )
                        .map_err(|e| lua_to_interop(&mut context.lua, e))?;
                    Ok(())
                }],
                language: Language::Lua,
                context_policy: ContextPolicy::shared(),
                emit_responses: false,
                processing_pipeline_plugin: Default::default(),
            },
        }
    }
}

impl Plugin for LuarsScriptingPlugin {
    fn build(&self, app: &mut App) {
        self.scripting_plugin.build(app);
    }

    fn finish(&self, app: &mut App) {
        self.scripting_plugin.finish(app);
    }
}

fn load_lua_content_into_context(
    context: &mut LuarsContext,
    context_key: &ScriptAttachment,
    content: &[u8],
    world_id: WorldId,
) -> Result<(), InteropError> {
    let config = LuarsScriptingPlugin::readonly_configuration(world_id);
    let initializers = config.context_initialization_callbacks;
    let pre_handling_initializers = config.pre_handling_callbacks;
    initializers
        .iter()
        .try_for_each(|init| init(context_key, context))?;
    pre_handling_initializers
        .iter()
        .try_for_each(|init| init(context_key, context))?;

    let source = str::from_utf8(content).map_err(InteropError::external)?;
    context
        .lua
        .load(source)
        .set_name(
            context_key
                .script()
                .path()
                .map(|p| p.to_string())
                .unwrap_or_else(|| "script".to_owned()),
        )
        .exec()
        .map_err(|e| lua_to_interop(&mut context.lua, e))?;
    Ok(())
}

fn luars_context_load(
    context_key: &ScriptAttachment,
    content: &[u8],
    world_id: WorldId,
) -> Result<LuarsContext, InteropError> {
    let mut context = LuarsContext::new()?;
    load_lua_content_into_context(&mut context, context_key, content, world_id)?;
    Ok(context)
}

fn luars_context_reload(
    context_key: &ScriptAttachment,
    content: &[u8],
    old_ctxt: &mut LuarsContext,
    world_id: WorldId,
) -> Result<(), InteropError> {
    load_lua_content_into_context(old_ctxt, context_key, content, world_id)?;
    Ok(())
}

fn luars_handler(
    args: Vec<ScriptValue>,
    context_key: &ScriptAttachment,
    callback_label: &CallbackLabel,
    context: &mut LuarsContext,
    world_id: WorldId,
) -> Result<ScriptValue, InteropError> {
    let config = LuarsScriptingPlugin::readonly_configuration(world_id);
    config
        .pre_handling_callbacks
        .iter()
        .try_for_each(|init| init(context_key, context))?;

    let handler: Option<LuaFunction> = context
        .lua
        .get_global(callback_label.as_ref())
        .map_err(|e| lua_to_interop(&mut context.lua, e))?;
    let Some(handler) = handler else {
        trace!(
            "Context {} is not subscribed to callback {}",
            context_key,
            callback_label.as_ref()
        );
        return Ok(ScriptValue::Unit);
    };

    let mapped: Vec<LuaScriptValue> = args.into_iter().map(LuaScriptValue).collect();
    handler
        .call::<_, MultiLuaScriptValue>(mapped)
        .map(MultiLuaScriptValue::into_script_value)
        .map_err(|e| lua_to_interop(&mut context.lua, e))
}

/// Convert a luars [`LuaError`] into a BMS [`InteropError`] using the VM's
/// stored message.
///
/// Prefer [`LuarsContext::map_lua`] when you already have a context. Use this
/// when you only have a [`Lua`].
pub fn into_bms_error(lua: &mut Lua, e: LuaError) -> InteropError {
    lua_to_interop(lua, e)
}