Function quickjs_runtime::quickjs_utils::functions::parse_function

source ·
pub unsafe fn parse_function(
    context: *mut JSContext,
    async_fn: bool,
    name: &str,
    body: &str,
    arg_names: Vec<&str>,
) -> Result<QuickJsValueAdapter, JsError>
Expand description

parse a function body and its arg_names into a JSValueRef which is a Function

§Example

use quickjs_runtime::esruntimebuilder::EsRuntimeBuilder;
use quickjs_runtime::quickjs_utils::functions::{parse_function, call_function};
use quickjs_runtime::quickjs_utils::primitives;
use quickjs_runtime::JsError::JsError;
use quickjs_runtime::valueref::JSValueRef;
let rt = EsRuntimeBuilder::new().build();
rt.add_to_event_queue_sync(|q_js_rt| {
    let q_ctx = q_js_rt.get_main_context();
    let func_res = parse_function(q_ctx.context, false, "my_func", "console.log('running my_func'); return(a * b);", vec!["a", "b"]);
    let func = match func_res {
        Ok(func) => func,
        Err(e) => {
            panic!("could not get func: {}", e);
        }
    };
    let a = primitives::from_i32(7);
    let b = primitives::from_i32(9);
    let res = call_function(q_ctx.context, &func, vec![a, b], None).ok().unwrap();
    let res_i32 = primitives::to_i32(&res).ok().unwrap();
    assert_eq!(res_i32, 63);
});

§Safety

when passing a context ptr please be sure that the corresponding QuickJsContext is still active