Skip to content

Instantly share code, notes, and snippets.

@torkleyy
Created October 29, 2017 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torkleyy/0a746bdeb51de45e97aa1f11c50c1972 to your computer and use it in GitHub Desktop.
Save torkleyy/0a746bdeb51de45e97aa1f11c50c1972 to your computer and use it in GitHub Desktop.
A little snippet showing how Lua could be used together with Specs.
#[macro_use]
extern crate error_chain;
extern crate hlua;
extern crate specs;
use std::collections::HashMap;
error_chain! {
errors {
NoSuchComponent(name: String) {
description("Requested component is not registered")
display("Requested component {:?} is not registered", name)
}
}
}
struct LuaComponent {
value: hlua::AnyLuaValue,
}
impl specs::Component for LuaComponent {
type Storage = specs::DenseVecStorage<Self>;
}
fn main() {
let mut component_map = HashMap::new(); // String -> id mapping with ids starting at 1
let mut world = specs::World::new();
{
let mut lua = hlua::Lua::new();
lua.set(
"world_register",
hlua::function1(|name: String| {
let len = component_map.len();
let id = len + 1;
component_map.insert(name, id);
world.register_with_id::<LuaComponent>(id);
}),
);
lua.execute::<()>("world_register(\"MyComp\")").unwrap();
}
println!("Components: {:#?}", &component_map);
assert_eq!(component_map.get("MyComp"), Some(&1));
{
let mut lua = hlua::Lua::new();
lua.set(
"read",
hlua::function1::<_, Result<_>, _>(|s: String| {
let &id: &usize = component_map
.get(&s)
.chain_err(|| ErrorKind::NoSuchComponent(s))?;
let comp = world.read_with_id::<LuaComponent>(id);
Ok(5) // TODO: implement `Push` for e.g. `LuaStorage`
}),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment