Skip to content

Commit ee30cf1

Browse files
authored
add coroutine example (#33)
1 parent 7d37342 commit ee30cf1

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,11 @@ name = "event_recipients_lua"
115115
path = "examples/lua/event_recipients.rs"
116116
required-features=["lua54"]
117117

118+
[[example]]
119+
name = "coroutines_lua"
120+
path = "examples/lua/coroutines.rs"
121+
required-features=["lua54"]
122+
118123
[[example]]
119124
name = "documentation_gen_lua"
120125
path = "examples/lua/documentation_gen.rs"

assets/scripts/coroutines.lua

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
local my_routine;
2+
3+
function on_update()
4+
5+
if my_routine == nil then
6+
my_routine = coroutine.create(function()
7+
local starttime = os.time()
8+
local endtime = starttime + 5
9+
while os.time() < endtime do
10+
print(os.date("waiting %H:%M:%S", os.time()))
11+
coroutine.yield()
12+
end
13+
14+
print(os.date("finished! %H:%M:%S", os.time()))
15+
end)
16+
else
17+
if coroutine.status(my_routine) ~= "dead" then
18+
coroutine.resume(my_routine)
19+
else
20+
print("Couroutine has finished, no longer running")
21+
end
22+
end
23+
24+
end

examples/lua/coroutines.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
use bevy::prelude::*;
2+
use bevy_mod_scripting::prelude::*;
3+
4+
/// fire on_update
5+
fn do_update(mut w: PriorityEventWriter<LuaEvent<()>>, time: Res<Time>) {
6+
let event = LuaEvent {
7+
hook_name: "on_update".to_owned(),
8+
args: (),
9+
recipients: Recipients::All,
10+
};
11+
info!(
12+
"\t - event: {}, time: {:?}",
13+
event.hook_name,
14+
(time.startup() + time.time_since_startup())
15+
);
16+
w.send(event, 0);
17+
}
18+
19+
fn load_our_scripts(server: Res<AssetServer>, mut commands: Commands) {
20+
let path = "scripts/coroutines.lua";
21+
let handle = server.load::<LuaFile, &str>(path);
22+
let script = Script::<LuaFile>::new(path.to_string(), handle);
23+
24+
commands.spawn().insert(ScriptCollection::<LuaFile> {
25+
scripts: vec![script],
26+
});
27+
}
28+
29+
fn main() -> std::io::Result<()> {
30+
let mut app = App::new();
31+
32+
app.add_plugins(DefaultPlugins)
33+
.add_plugin(ScriptingPlugin)
34+
.add_startup_system(load_our_scripts)
35+
// randomly fire events for either all scripts,
36+
// the script with id 0
37+
// or the script with id 1
38+
.add_system(do_update)
39+
.add_script_handler_stage::<LuaScriptHost<()>, _, 0, 0>(CoreStage::PostUpdate)
40+
.add_script_host::<LuaScriptHost<()>, _>(CoreStage::PostUpdate);
41+
app.run();
42+
43+
Ok(())
44+
}

0 commit comments

Comments
 (0)