summaryrefslogtreecommitdiff
path: root/src/lua/ownedfunction.rs
blob: 54e39df3f10e8b5594b7ae3e8c7b22eb374a8b6d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
use mlua::{Error, FromLua, Function, Lua, RegistryKey, Value};

#[derive(Debug)]
pub struct OwnedFunction {
    key: RegistryKey,
}

impl OwnedFunction {
    pub fn new<'lua>(value: Value<'lua>, lua: &'lua Lua) -> Self {
        let key = lua.create_registry_value(value).unwrap();
        Self { key }
    }

    pub fn get<'lua>(&self, lua: &'lua Lua) -> Function<'lua> {
        lua.registry_value(&self.key).unwrap()
    }
}

impl<'lua> FromLua<'lua> for OwnedFunction {
    fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> mlua::prelude::LuaResult<Self> {
        if value.is_function() {
            Ok(OwnedFunction::new(value, lua))
        } else {
            Err(Error::runtime("value needs to be function"))
        }
    }
}