use anyhow::{Result, anyhow};
use mlua::prelude::*;
use crate::{lua::{from_lua, into_lua}, shared::{pxs_Runtime, func::call_function, var::pxs_Var}};
pub(super) fn internal_add_callback(lua: &Lua, fn_idx: i32) -> Result<LuaFunction> {
let func = lua.create_function(move |lua, args: LuaMultiValue| -> Result<LuaValue, LuaError> {
let mut argv: Vec<pxs_Var> = vec![];
argv.push(pxs_Var::new_i64(pxs_Runtime::pxs_Lua as i64));
for arg in args {
let lua_arg = from_lua(arg);
if lua_arg.is_err() {
return Err(LuaError::RuntimeError(lua_arg.unwrap_err().to_string()));
}
argv.push(lua_arg.unwrap());
}
unsafe {
let res = call_function(fn_idx, argv);
let lua_val = into_lua(lua, &res);
lua_val
}
});
if func.is_err() {
Err(anyhow!(func.unwrap_err().to_string()))
} else {
Ok(func.unwrap())
}
}