use mlua::{IntoLua, Lua, Table, Value};
use crate::error::{Error, Result};
pub fn nitr_table(lua: &Lua) -> Result<Table> {
let globals = lua.globals();
match globals.get::<Value>("nitr")? {
Value::Table(t) => Ok(t),
Value::Nil => {
let t = lua.create_table()?;
globals.set("nitr", &t)?;
Ok(t)
}
other => Err(Error::Script(format!(
"the global `nitr` must be the namespace table, found {}",
other.type_name()
))),
}
}
pub const EXT_TABLE: &str = "ext";
pub fn ext_table(lua: &Lua) -> Result<Table> {
let nitr = nitr_table(lua)?;
match nitr.get::<Value>(EXT_TABLE)? {
Value::Table(t) => Ok(t),
Value::Nil => {
let t = lua.create_table()?;
nitr.set(EXT_TABLE, &t)?;
Ok(t)
}
other => Err(Error::Script(format!(
"`nitr.{EXT_TABLE}` must be the extension table, found {}",
other.type_name()
))),
}
}
pub fn mount(lua: &Lua, name: &str, value: impl IntoLua) -> Result {
let ext = ext_table(lua)?;
if ext.get::<Value>(name)? != Value::Nil {
return Err(Error::Script(format!(
"cannot register the module `{name}`: `nitr.{EXT_TABLE}.{name}` already exists"
)));
}
ext.set(name, value)?;
Ok(())
}
pub type ModuleFn = dyn Fn(&Lua) -> mlua::Result<Table> + Send + Sync;