[solved][JS] how to modify the property accessing mechanics of an object



  • Hi everyone,

    I discorvered Screeps few days ago (and JS with it...), I already know programming metaclasses with python.

    I would like to make an object which is basically a simple alias, the goal is to work with Memory.

    let says that we set this :

    Memory.myGlobals = {};

    Let's imagine that I create the object that act as an alias (as in C), and name its instance '_glob'

    in the end, typing this :

    _glob.stuff = 1;

    have to be the same as

    Memory.myGlobals.stuff = 1

     

    While in python I would play with a metclass overriding the attribute accessing of the targeted class to re-route any of its attribute request towards Memory.myGlobals, In JS I just can't figure it out !

    I tried to grasp the getters and setters, but it only applies on one property, not just any...

    I made something else, but the way it is used is... well, not as convenient as what I want to acheive.

    In pseudo-code, the core of the idea should give that

    Memory.myGlobals = {};

    function Alias(){
    this.__classAttributGetter__ = function(attributeName){
    return Memory.myGlobals[attributeName];};
    }

    alias = new Alias();
    alias.stuff = [];
    alias.stuff.push(1);

     

    SO, would you know how to do this ?

     

     



  •  

    To set an alias, just set  _glob = Memory.myGlobals at the beginning of every tick. Since they will point to the same object, changes in one will reflect in the other. You could also tinker around with the property accessors, but I think in this case it's not necessary.



  • Really ? Just like that ?

    I feel so dumb...

    I just assumed that because objects stored in Memory were serialized / "stringified" / whatever, objects like arrays and "dictionaries" ( {a:1,...} ) , any property request on Memory would return a duplicate of the value...

    And your statement made me understand that the console  only evaluate expressions (this, kinda sucks)

    Well, that reminds me a lesson : don't overthink things, try & see...

    Thanks pal 🙂



  • The objects in the Memory are serialized, but only between ticks. Inside one tick, Memory is a prefectly normal object. It confused me too at the beginning 🙂

    Edit: That's why it's important that you renew the alias inside the main function, so it's done every tick.

    If you write outside a function var _alias = Memory.myGlobals, it is only executed every ~15 ticks (when the global context is reloaded), and won't work.



  • Ahhhhhhh.... okay, now that makes sense... yup, confusing it was indeed. 🙂