Restructure lua file

This commit is contained in:
Dane Johnson 2022-04-15 20:16:57 -05:00
parent 267188a571
commit d22584c44e

View File

@ -14,6 +14,51 @@ pub struct Lua {
ctx: LuaContext,
}
impl Lua {
pub fn new(root: Rc<RefCell<Node>>) -> 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<RefCell<Node>>) -> 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();
}
}