What is the process for accessing external variables from Cheerp/js?

Cheerp is a tool that transpiles C++ code to js/wasm. Screeps is an interactive programming game.

How can I access the Game.time variable in my C++ code after it has been transpiled for Screeps?


#include <cheerp/client.h>
#include <iostream>
using namespace std;

namespace client {
    class Game : public Object {
    public:
        static volatile double time;
    };  

    extern volatile Game &Game;
}

void webMain() {
    cout << __TIME__ << ": The current time is: " << client::Game.time << endl;
}

I have experimented with:

  • extern, volatile, and static keywords
  • references and pointers
  • both client and cheerp namespaces
  • Inheriting from Node/Object
  • Different data types such as int32_t, double, and float

However, I keep encountering issues like:

  • NaN
  • 0
  • 1
  • fatal errors related to data types in the compiled code

What is the correct approach to interact with JavaScript objects and variables from C++ code? The documentation provided by cheerp is very limited...


Note: It seems that cheerp is not generating the correct JavaScript output. There are inconsistencies in how the Game object is handled, leading to attempts to index Game.d as an array rather than Game.time.

Answer №1

It is recommended that classes declared within the client namespace do not contain any member fields.

In order to access properties of external JavaScript objects, you must include methods starting with get_ and set_, which are used for reading and writing to the property respectively:

#include <cheerp/client.h>
#include <iostream>
using namespace std;

namespace client {
    class Game : public Object {
    public:
        double get_time();
    };  

    extern Game &Game;
}

void webMain() {
    cout << __TIME__ << ": The current time is: " << client::Game.get_time() << endl;
}


Additionally, there is no need to utilize the `volatile` keyword in this context.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing issues with passwords in nodemailer and node

Currently, I am utilizing nodemailer in conjunction with Gmail and facing a dilemma regarding the inclusion of my password. The predicament stems from the fact that my password contains both single and double quotes, for example: my"annoying'password. ...

Issue with updating state following data retrieval in React hooks

Recently, I've been experimenting with an API and working on a React application for data display. However, I encountered an issue while setting the state using the setState method of React Hooks after sending my information through a form request via ...

Using AngularJS and $http PUT method to send files in the request body

I am currently facing an issue with uploading files via an API call using the PUT method. After successfully uploading a file, I am encountering problems where the resulting file size is larger than expected and cannot be opened. For example, a 234 kb jpg ...

The static files for the icon CSS (404 Error) from Flaticon and Font-mfizz are failing to load properly

When I was designing a website, I needed an icon of Python, so I turned to Flaticon and found what I was looking for. This snippet shows the HTML code I used: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <li ...

The action of JQuery is modifying the value of the checkbox, but it is not visually showing as checked

I am working on a list that contains checkboxes and text, similar to an email inbox. My goal is to be able to check or uncheck the checkbox anytime I click anywhere on the list item (row). To achieve this functionality, I have used the following code withi ...

Tips on implementing v-show within a loop

Hey @zero298, there are some key differences in the scenario I'm dealing with. My goal is to display all the items in the object array and dynamically add UI elements based on user input. Additionally, v-if and v-show function differently (as mentione ...

How can I ensure that the state is only updated after the map function has finished executing in React?

I am encountering an issue with updating the state after mapping over an array of ids using an async function. The goal is to store the result in newArr and then update the state via setState. However, the state is being updated before the mapping operatio ...

The React Native Expo is throwing an error stating that it is unable to locate the module 'minizlib'

At the instructions available in the read.me of https://github.com/react-community/create-react-native-app Upon selecting my template using the expo init command, I encountered the following error: Cannot find module 'minizlib' Error: Cannot fi ...

Issues with @material-ui/core and react-bootstrap imports are causing disruptions to the NextJS build process

After researching, I've come to realize that this issue is common among developers. Unfortunately, none of the solutions I found have worked for me. During npm run dev mode, everything in the project functions as expected, with all imports working se ...

How to manage access controls for the Admin Page in node.js

Hi everyone, I am facing an issue with my admin page access control on my application. I want to restrict access to all users except the one named John. In my app.js file, here is what I have: app.get('/admin', requireLogin, function(req, res){ ...

Conceal pagination numbers using jquery pagination

I have integrated a jquery function to handle pagination of items on my website. Below is the function code: (function($) { var pagify = { items: {}, container: null, totalPages: 1, perPage: 3, ...

Cross-Origin Resource Sharing (CORS) for HTML

Here is a code snippet I found on http://jakearchibald.com/scratch/alphavid/ $("#video").append('<video id="movie" style="display:none" autobuffer><source id="srcMp4" src="https://host-away-from-host.com/file.mp4" type=\'video/mp4; ...

Enhancement from the original JavaScript class framework created by John Resig

Greetings everyone, Lately, I've been on the lookout for a straightforward JavaScript class framework that focuses solely on basic inheritance. After some research, I stumbled upon John Resig's sample framework shared on his blog, and it seems t ...

What is the best way to retrieve a key from an Any type in Angular?

Currently, I am facing a challenge in extracting key values from an Any type while working with Angular/Typescript. For instance, if another segment of the program is providing this data: { Amy: { age: 7, grade: 2 }, Max: { ...

AngularJS triggers after the completion of Ajax requests

How can I implement AJAX within Angular AJAX? In my Angular setup, it looks like this: Index.html MyApp.controller('MainController', function($scope, $http, $location , $compile) { $scope.content_middle = 'Welcome'; ...

Is it possible for Spring Boot to initiate an action that will dynamically update an image in an HTML document using JavaScript or another method?

I am currently facing a challenge in updating an image on a website built with HTML, while utilizing Spring Boot as the backend technology. As of now, I am using JavaScript to update the image at regular intervals, but the timing does not align with when t ...

Comparing Arrays with jQuery

I am currently working on a tic-tac-toe project that involves a simple 3x3 grid. I have been storing the index of each selected box in an array for each player. However, I am facing difficulty in comparing my player arrays with the winner array to determin ...

Navigate to the specified location using AJAX

When I update a comment using AJAX, I want to automatically scroll down to the updated comment: $("#aggiorna").click(function(){ var value = $("#id").val(); var dato = $("#comment_edit").val(); var dato1 = $("#user_id").val(); var dato2 = ...

Error message in Jquery function: Uncaught TypeError - undefined property 'noDisagree'

Hey there! I am attempting to invoke a function in an AngularJs controller with a parameter using Jquery, but unfortunately encountering the error: Uncaught TypeError: Cannot read property 'noDisagree' of undefined function noDisagree(id){ ...

Issue with Setting Value in JQuery Select Box

I am in the process of designing a webpage that allows users to edit listings they have created on my website. These listings fall under three main categories, each with its own set of subcategories. To streamline this process, I am implementing AJAX to dy ...