engine: add scripting worldcontext

master
q3k 2021-04-04 20:22:33 +00:00
parent 630073f916
commit 8d4bac00cf
3 changed files with 37 additions and 0 deletions

View File

@ -14,6 +14,7 @@ rust_binary(
"src/main.rs",
"src/input.rs",
"src/scripting.rs",
"src/physics/mod.rs",
"src/physics/color.rs",
@ -46,6 +47,7 @@ rust_binary(
"//lib/ecs",
"//third_party/cargo:cgmath",
"//third_party/cargo:image",
"//third_party/cargo:mlua",
"//third_party/cargo:winit",
"//third_party/cargo:log",
"//third_party/cargo:env_logger",

View File

@ -25,6 +25,7 @@ pub mod input;
mod render;
mod util;
mod physics;
mod scripting;
use ecs::{Component, World, Processor};
use ecs_macros::Access;
@ -217,6 +218,9 @@ fn main() {
let mut renderer = render::Renderer::initialize(&mut world);
let main = Main::new(&mut world, &mut renderer);
let context = scripting::WorldContext::new();
context.eval("print(\"Hello, Lua!\", 1337)").unwrap();
log::info!("Starting...");
let mut p = Processor::new(&world);

31
engine/src/scripting.rs Normal file
View File

@ -0,0 +1,31 @@
pub struct WorldContext {
lua: mlua::Lua,
}
fn debug_str(v: &mlua::Value) -> String {
match v {
mlua::Value::String(s) => s.to_str().map_or(format!("{:?}", v), |s| s.to_string()),
mlua::Value::Integer(i) => format!("{}", i),
_ => format!("{:?}", v),
}
}
impl WorldContext {
pub fn new() -> Self {
let lua = mlua::Lua::new();
log::info!("Lua WorldContext created.");
lua.globals().set("print", lua.create_function(|_, vals: mlua::Variadic<mlua::Value>| -> mlua::Result<()> {
let msg: Vec<String> = vals.iter().map(|val| debug_str(val)).collect();
log::info!("[Lua] {}", msg.join("\t"));
Ok(())
}).unwrap()).unwrap();
Self {
lua,
}
}
pub fn eval(&self, val: &str) -> mlua::Result<()> {
self.lua.load(val).exec()
}
}