diff --git a/src/scripting/lua.rs b/src/scripting/lua.rs index 2b21528..8b1a721 100644 --- a/src/scripting/lua.rs +++ b/src/scripting/lua.rs @@ -14,6 +14,51 @@ pub struct Lua { ctx: LuaContext, } +impl Lua { + pub fn new(root: Rc>) -> Self { + // Create a lua context, load std libraries + let ctx = LuaContext::new(); + // Create the ``couch'' api + let couch = ctx.create_table().unwrap(); + couch.set("root", ctx.create_userdata(root).unwrap()).unwrap(); + // Hook in to globals + ctx.globals().set("couch", couch).unwrap(); + let path = std::path::Path::new("main.lua"); + let buf = std::fs::read(&path).expect("Could not find main.lua"); + ctx.load(&buf).exec().unwrap(); + + Lua { + ctx, + } + } +} + +impl ScriptLang for Lua { + fn init(&mut self) { + self.ctx.load(chunk! { + if couch.init then couch.init() end + }).exec().unwrap(); + } + + fn update(&mut self, delta: f32) { + self.ctx.load(chunk! { + if couch.update then couch.update($delta) end + }).exec().unwrap(); + } + + fn key_pressed(&mut self, key: u32) { + self.ctx.load(chunk! { + if couch.keypressed then couch.keypressed($key) end + }).exec().unwrap(); + } + + fn key_released(&mut self, key: u32) { + self.ctx.load(chunk! { + if couch.keyreleased then couch.keyreleased($key) end + }).exec().unwrap(); + } +} + impl mlua::UserData for Node { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { methods.add_method_mut("find_node", |_, this, name: String| { @@ -65,48 +110,3 @@ impl<'lua> mlua::FromLua<'lua> for Transform { } } } - -impl Lua { - pub fn new(root: Rc>) -> Self { - // Create a lua context, load std libraries - let ctx = LuaContext::new(); - // Create the ``couch'' api - let couch = ctx.create_table().unwrap(); - couch.set("root", ctx.create_userdata(root).unwrap()).unwrap(); - // Hook in to globals - ctx.globals().set("couch", couch).unwrap(); - let path = std::path::Path::new("main.lua"); - let buf = std::fs::read(&path).expect("Could not find main.lua"); - ctx.load(&buf).exec().unwrap(); - - Lua { - ctx, - } - } -} - -impl ScriptLang for Lua { - fn init(&mut self) { - self.ctx.load(chunk! { - if couch.init then couch.init() end - }).exec().unwrap(); - } - - fn update(&mut self, delta: f32) { - self.ctx.load(chunk! { - if couch.update then couch.update($delta) end - }).exec().unwrap(); - } - - fn key_pressed(&mut self, key: u32) { - self.ctx.load(chunk! { - if couch.keypressed then couch.keypressed($key) end - }).exec().unwrap(); - } - - fn key_released(&mut self, key: u32) { - self.ctx.load(chunk! { - if couch.keyreleased then couch.keyreleased($key) end - }).exec().unwrap(); - } -}