Skip to content

Example: DynamicArray

Craig Minihan edited this page Apr 28, 2015 · 7 revisions

In JSAPI arrays are static objects: you must size and populate them in advance. With libjsapi we have added the concept of a dynamic array implemented in the DynamicArray class.

The libjsapi DynamicArray is not really a JS array at all, it is implemented as an object which assumes that access via [ ] is a index and also exposes a length read-only property. So the following JS code will work as you expect:

for (var i = 0; i < arr.length; ++i) {
  alert(arr[i]);
}

Since DynamicArray is not a true JS array it is missing Array functions like push, pop, etc.

The following example outputs the Fibonacci number sequence to the console:

#include <iostream>
#include <vector>

#include "libjsapi.h"

int main() {
    std::vector<int> data = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 };

    rs::jsapi::Runtime rt;

    // create a dynamic array which exposes the `data` vector to JS
    rs::jsapi::Value array(rt);
    rs::jsapi::DynamicArray::Create(rt,
        [&](int index, rs::jsapi::Value& value) { value.set(data[index]); return true; },
        nullptr,
        [&]() { return data.size(); },
        nullptr,
        array);

    // create a function which returns the value of the item 'n'
    // on the passed array
    rt.Evaluate("var myfunc=function(arr, n){ return arr[n]; }");

    rs::jsapi::FunctionArguments args(rt);
    args.Append(array);
    args.Append(0);

    // invoke the function and get the value of the index i
    for (int i = 0; i < data.size(); ++i) {
        args[1].setInt32(i);

        rs::jsapi::Value result(rt);
        rt.Call("myfunc", args, result);

        std::cout << result << std::endl;
    }

    return 0;
}

Executing this example yields the following output:

1
1
2
3
5
8
13
21
34
55
89
144
Clone this wiki locally