bile 0.1.0

A simple build system, structured around Lua scripts.
//! Specification of the core api exposed to Lua.
//!
//! See also the `impl` of [`UserData`] for [`Module`](`crate::Module`).

use mlua::{Error as LuaError, Lua, LuaOptions, StdLib, UserData, UserDataMethods};

/// The library that gets exposed to Lua.
pub struct LibBuilder;

impl LibBuilder {
    /// Add `LibBuilder` to a Lua environment as "builder".
    ///
    /// # Errors
    ///
    /// This function will return an error if creating a Lua "proxy" fails or if
    /// setting the "builder" key in the lua globals table fails.
    pub fn add_to_lua_globals(lua: &Lua) -> Result<(), LuaError> {
        lua.globals().set("builder", lua.create_proxy::<Self>()?)
    }

    /// Builds a Lua runtime with a minimal subset of the standard libraries
    /// plus [`LibBuilder`] avaliable.
    ///
    /// The avaliable standard libraries are [`StdLib::MATH`],
    /// [`StdLib::STRING`], [`StdLib::TABLE`], and [`StdLib::BIT`].
    ///
    /// > Note: Lua's built in `print(...)` is disabled.
    ///
    /// # Errors
    ///
    /// This function will return an error if adjusting Lua's globals fails. Or
    /// if somehow [`Lua::new_with`] decides one of our libraries is unsafe and
    /// denies us passage.
    pub fn init_lua() -> Result<Lua, LuaError> {
        let lua = Lua::new_with(
            StdLib::MATH | StdLib::STRING | StdLib::TABLE | StdLib::BIT,
            LuaOptions::new(),
        )?;

        lua.globals().raw_remove("print")?;

        Self::add_to_lua_globals(&lua)?;

        Ok(lua)
    }
}

impl UserData for LibBuilder {
    fn add_methods<M: UserDataMethods<Self>>(_methods: &mut M) {}
}