Search code examples
c++lua-apiduktape

duktape closure registration


I have C++ project and I'm using duktape JS library. I need to register global function in JS and save pointer to object as closure data with this function, so I can access this pointer when function is called.

I know how to do this in lua c api:

lua_pushlightuserdata(L, this);
lua_pushcclosure(L, &someFunction, 1);
lua_setglobal(L, "someFunction");

First I'm pushing pointer as closure data, then pointer to function. I need same functionality in duktape api.

Can you show me some code with closure registration and accessing it?


Solution

  • There is no direct analogy to values associated with a "C closure" but you can achieve a similar result in other ways.

    One simple way is to store the value as a property of the function instance:

    duk_push_c_function(ctx, someFunction, 1 /*nargs*/);
    duk_push_pointer(ctx, (void *) somePointer);
    duk_put_prop_string(ctx, -2, "_ptr");
    duk_put_global_string(ctx, "someFunction");
    

    Then, when the function is called, retrieve the value as:

    void *ptr;
    
    duk_push_current_function(ctx);
    duk_get_prop_string(ctx, -1, "_ptr");
    ptr = duk_get_pointer(ctx, -1);
    duk_pop_2(ctx);  /* pop pointer and function */
    
    /* ready to use 'ptr' */
    

    If you want to limit access to the associated value from Ecmascript code, you can use an internal string, e.g. "\xFF" "ptr".