[Solved] Correct implementation of function library



  • Hello!

    I'm trying to give a better organization to my functions, in order to have a more polished code and to reduce wastes in module loadings.

    So far I wanted to implement a module containing all the most common functions my creeps could need to use, but after that I find myself trapped in the need to include the function module in every other module I need to use it in.

    Isn't there a way to include a library once, like in the main loop, and then use the functions in every other script like it was global?

    Moreover, if I write a separate file to add prototype extensions, how do I include that file in my other modules, since I only know how to require modules as the documentation shows?

    Thanks in advance for the help and have an happy screepsing! 🙂



  • Hi, 

    there is a 'global' object. 

    In your main loop try: 

    global.common = require('common');

    Then you can use

    common.whatever() 

    whereever you need (assumed 'whatever' is a function in your common library).



  • Now I feel stupid not having thought about that. 🙂

    Many thanks my friend, may your creeps overrun your enemies and lay waste to their bases! 🙂



  • You're welcome!

    They will surely try to 😉 

    have fun



  • To include the prototype extensions, you include the module by require(...) as usual, and save it in a dummy variable, if you don't use the module otherwise.



  • > all the most common functions my creeps could need to use

     

    This sounds like you should expand the according prototype:

     

    main.js

     

    ```

    require("Prototype_Creep");

    ```

    Prototype_Creep.js

     

    ```

        _.assign(Creep.prototype,{

            get : function(val){return this.memory[val]},

         });

    // or another way to write:

    Object.defineProperties(Creep.prototype,{

        "costs" : { get : costs },
        "Class" : { get : function(){return this.get("Class");}},
        "type" : { get : function(){return this.get("type");}},
        "task" : { get : function(){return this.get("task");}},
        MAX_LIFE : { value: CREEP_LIFE_TIME, enumerable:false,writable:false},
        MAX_BODYPARTS : { value: MAX_CREEP_SIZE , enumerable:false,writable:false},
    });

    ```

     

     



  • I'm on holiday, so I forgot to login here too to say thanks for other answers!

    Thanks for the hints about how to include my files with prototype extensions! 😄

    I converted most of my common functions into new functions extending Creep prototype and I must say I'm quite satisfied by the result, except for the CPU weight on module loading. But I'll open a new thread for that, since it's a separate topic.

    Many thanks again to all of you who helped my out. 🙂