-
Notifications
You must be signed in to change notification settings - Fork 3
Example: DynamicArray
JSAPI
arrays are static objects which have fixed size and must be populated in advance. In libjsapi
we have added a dynamic array type implemented in the DynamicArray
class, this class has getter/setter callbacks in addition to a length callback. The values exposed by this type are evaluated as the JavaScript is executed so the array instance does not have to be populated in advance.
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::Context cx;
// create a dynamic array which exposes the `data` vector to JS
rs::jsapi::Value array(cx);
rs::jsapi::DynamicArray::Create(cx,
[&](int index, rs::jsapi::Value& value) { value = data[index]; },
nullptr,
[&]() { return data.size(); },
nullptr,
array);
// create a function which returns the value of the item 'n'
// on the passed array
cx.Evaluate("var myfunc=function(arr, n){ return arr[n]; }");
// create an arguments instance so we can call the JS function
rs::jsapi::FunctionArguments args(cx);
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(cx);
cx.Call("myfunc", args, result);
std::cout << result << std::endl;
}
}
Executing this example yields the following output:
1
1
2
3
5
8
13
21
34
55
89
144