API: JS: Getting Started - ov-studio/Vital.sandbox GitHub Wiki
Vital increases your productivity by providing straightforward optimized custom JS bindings for C++ interface.
Looking to embed js
in your game project? game engine? sandbox (multiple js resources?)? Don't worry, we've crafted it to suite the requirements of various projects.
Our abstraction layer supports creation/management of multiple vm's, custom error handling, dynamic interface bindings; Just embed and get started!
-
Attach an error handler as per requirements as per binding.
For example an error handler that prints the outputs to console would look something similar:
// Import our header file #include <Sandbox/js/public/api.h> Vital::Sandbox::JS::API::onErrorHandle([](std::string& err) -> void { std::cout << "\nError" << err; });
-
Bind your C++ functions that you prefer to expose to JS as per binding.
For example a JS function called
greetMe
that greets by accepting name as parameter would look something similar:var result = greetMe("World") print(result) // "Hello World"
Vital::Sandbox::JS::API::bind("__G", "greetMe", [](vital_ref* ref) -> int { auto vm = Vital::Sandbox::JS::fetchVM(ref); // Fetches vm by state's reference return vm -> execute([&]() -> int { std::string name = vm -> getString(-1) // Get the topmost (i.e, value at index -1) string from the vm's stack std::string result = "Hello " + name; // Create a result "Hello <name>" vm -> setString(result); // Push the result to vm's stack return 1; // Result is defined and existing thus returning 1 }); });
-
Since we've got error handler and our bindings ready, its time to boot them as indicated below:
Vital::Sandbox::JS::API::boot(); // Boots the bindings and custom libraries provided by Vital
-
Hurray! Its finally time to create a VM as per vm and test our application:
std::string testScript = R"( print(greetMe("Aviril")) print(greetMe("Аниса")) print(greetMe("Tron")) print(greetMe("Mario")) )"; auto testVM = new Vital::Sandbox::JS::create(); testVM -> loadString(testScript); // Executes our string on the vm
Hello Aviril Hello Аниса Hello Tron Hello Mario
We've implemented our custom modules to highly upgrade js internally. By default JS's deprived of threader, namespaces, classes, filesystem, crypto (hashing, encoding/decoding, encrypting/decrypting) etc features; We integrate and provide them out of the box for you.
Although its not just limited to that, we've extended and improved existing modules to have more appropriate sandboxing features from engine perspective, such as quaternion
, matrix
libraries etc under math
module. All of the modules that we've implemented are completely from scratch and performance oriented.
You can read about each modules in-detail by navigating under 'Sandbox - JS` section.
Kindly refer the sidebar 👉🏻 under JS section for further details that you prefer to dive into.
For further native API reference refer: https://www.w3schools.com/js