1

Cheerp is a C++ to js/wasm transpiler. Screeps is a programming videogame.

How do I read in the Game.time variable from my transpiled C++ code? (in 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 tried any number of variations on:

  • extern, volatile and static
  • references and pointers
  • both client and cheerp namespaces
  • Inheriting from Node/Object
  • int32_t vs double vs float as a type

I seem to get either:

  • NaN
  • 0
  • 1
  • fatal type handling errors in the compiled code

How do I correctly interface with Javascript Objects and variables from within my C++ code? The cheerp documentation is VERY sparse to say the least...


Note: cheerp is never actually generating the proper Javascript. There's always some inconsistency as to how the Game object is handled and in a lot of scenarios it's incorrectly trying to index Game.d as an array instead of Game.time.

sbabbi
  • 11,070
  • 2
  • 29
  • 57
Xunie
  • 437
  • 4
  • 21
  • This question MAY be identical to: https://stackoverflow.com/questions/56853261/how-to-preserve-variable-name-in-cheerp-a-c-to-javascript-transpiler – Xunie Jun 15 '20 at 07:37

1 Answers1

3

Classes declared in the client namespace should have no member fields.

To access external JS objects properties you need to add methods starting with get_ and set_, to respectively read and write to the property:

#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;
}


Also, you don't need to use volatile here.

Yuri
  • 351
  • 1
  • 5
  • But what about arrays or complex types? How does that work? – Xunie Jun 15 '20 at 10:57
  • 1
    you can use pointers to basic types for arrays, and pointers to other client objects for nested objects: https://pastebin.com/DqTT8LN0 – Yuri Jun 15 '20 at 11:15