1. Omar El Sayyed
  2. Addaadah Engine

Source

Addaadah Engine / Source / Tests / Hello Duktape / Source / main.c


#include <Duktape/duktape.h>

#include <stdio.h>

duk_ret_t double_And_Print_Number(duk_context *ctx) {

    // Require a number at index 0 (function arguments index, not stack), throw otherwise,
    double number = duk_require_number(ctx, 0 /*index*/);
    
    // Perform the function,
    double doubledNumber = number * 2;
    printf("Received: %f, returned: %f\n", number, doubledNumber);
    
    // Push the new number in the stack,
    duk_push_number(ctx, doubledNumber);
    
    // Inform the caller of the return value,
    return 1;
}

int main() {

    // Create a heap,
    duk_context *ctx = NULL;
    ctx = duk_create_heap_default();
    if (!ctx) {
        printf("Failed to create a Duktape heap.\n");
        return 1;
    }

    // Push the Javascript global object into the stack (window),
    duk_push_global_object(ctx);
    
    // Push the native function,
    duk_push_c_function(ctx, double_And_Print_Number, 1 /*number of arguments*/);
    
    // Define the a property in the object whose index from the top is -2 (window), whose
    // name is "doubleAndPrintNumber" and value is whatever is on the top of the stack. It then
    // pops the top of the stack,
    duk_put_prop_string(ctx, -2, "doubleAndPrintNumber");

    // Run this string (peval is a protected version of eval),
    if (duk_peval_string(ctx, "var foo = function(number) { return doubleAndPrintNumber(number); };")) {
        printf("eval failed: %s\n", duk_safe_to_string(ctx, -1));
    
        // Pop the error string from the stack,
        duk_pop(ctx);
    } else {
        // Success, but we don't really need to do anything.
        // Pop the result from the stack,
        duk_pop(ctx);
    }

    // We've just created a new function foo that calls doubleAndPrintNumber, lets use it,
    if (duk_peval_string(ctx, "foo(foo(12));")) {
        printf("eval failed: %s\n", duk_safe_to_string(ctx, -1));
        duk_pop(ctx);
    } else {
        duk_pop(ctx);
    }

    // Destroy the heap,    
    duk_destroy_heap(ctx);
}