Function quickjs_runtime::quickjs_utils::functions::new_function_q
source · pub fn new_function_q<F>(
q_ctx: &QuickJsRealmAdapter,
name: &str,
func: F,
arg_count: u32,
) -> Result<QuickJsValueAdapter, JsError>where
F: Fn(&QuickJsRealmAdapter, &QuickJsValueAdapter, &[QuickJsValueAdapter]) -> Result<QuickJsValueAdapter, JsError> + 'static,
Expand description
create a new Function which is backed by a closure
§Example
use quickjs_runtime::builder::QuickJsRuntimeBuilder;
use quickjs_runtime::jsutils::Script;
use quickjs_runtime::quickjs_utils::functions::new_function_q;
use quickjs_runtime::quickjs_utils::primitives::from_i32;
use quickjs_runtime::quickjs_utils::get_global_q;
use quickjs_runtime::quickjs_utils::objects::set_property_q;
let rt = QuickJsRuntimeBuilder::new().build();
rt.exe_rt_task_in_event_loop(|q_js_rt| {
let q_ctx = q_js_rt.get_main_realm();
// create a function which always returns 1253
let func_obj = new_function_q(q_ctx, "myFunc7654", |_q_ctx, _this, _args|{Ok(from_i32(1253))}, 0).ok().unwrap();
// store as a global member so script can call it
let global = get_global_q(q_ctx);
set_property_q(q_ctx, &global, "myFunc7654", &func_obj).expect("set prop failed
");
});
rt.eval_sync(None, Script::new("new_function_q.es", "let a = myFunc7654(); if (a !== 1253) {throw Error('a was not 1253')}")).ok().expect("script failed");