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
/*
* This file is part of laurelin/client
* Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
*
* Licensed under GPL-3.0-only.
* See LICENSE for licensing information.
*/
use std::sync::Mutex;
use bevy_mod_scripting::prelude::*;
use bevy::prelude::*;
use bevy_console::PrintConsoleLine;
pub struct LuaPlugin;
impl Plugin for LuaPlugin {
fn build(&self, app: &mut App) {
app.add_startup_system(load_scripts)
.add_script_host::<LuaScriptHost<()>, _>(CoreStage::PostUpdate)
.add_script_handler_stage::<LuaScriptHost<()>, _, 0, 0>(CoreStage::PostUpdate)
.add_api_provider::<LuaScriptHost<()>>(Box::new(LuaAPIProvider))
.add_api_provider::<LuaScriptHost<()>>(Box::new(LuaBevyAPIProvider));
}
}
fn load_scripts(asset_server: Res<AssetServer>, mut commands: Commands) {
let script_paths = vec!["ui_play.lua"];
let mut scripts = vec![];
for path in script_paths {
let handle = asset_server.load::<LuaFile, &str>(&format!("scripts/{}", path));
scripts.push(Script::<LuaFile>::new(path.to_string(), handle));
}
commands
.spawn(())
.insert(ScriptCollection::<LuaFile> { scripts });
}
pub struct LuaAPIProvider;
impl APIProvider for LuaAPIProvider {
type APITarget = Mutex<Lua>;
type DocTarget = LuaDocFragment;
type ScriptContext = Mutex<Lua>;
fn attach_api(&mut self, api: &mut Self::APITarget) -> Result<(), ScriptError> {
let api = api.get_mut().unwrap();
api.globals()
.set(
"print_to_console",
api.create_function(|ctx, msg: String| {
// retrieve the world pointer
let world = ctx.get_world()?;
let mut world = world.write();
let mut events: Mut<Events<PrintConsoleLine>> =
world.get_resource_mut().unwrap();
events.send(PrintConsoleLine::new(msg.into()));
Ok(())
})
.map_err(ScriptError::new_other)?,
)
.map_err(ScriptError::new_other)?;
api.globals()
.set(
"print",
api.create_function(|_ctx, msg: String| {
info!("{}", msg);
Ok(())
})
.map_err(ScriptError::new_other)?,
)
.map_err(ScriptError::new_other)?;
Ok(())
}
}