Search code examples
squirrel

how to define a variable in a class, and pass it into a function


So im writing a script for the computer game Counter Strike: Global Offensive that changes a players crosshair ingame. the language the games engines uses is called Vscript. Vscript is not very well documented, with the only documentation i could fined being a long list of functions. But after trial an error, I found the syntax is almost identical to JavaScript, with the only real diffrences being that there are specific functions in the language like SetHealth or GetTeam for example that are specific to the game and dont exist in JavaScript.

class crosshair_generator {
    // Initialize
    crosshair_hidden = false;

    function hideCrosshair() {
        if (crosshair_hidden == true) {
            // Hide the crosshair 
            SendToConsole("crosshair 0");
            printl("crosshair hidden!");
            self.crosshair_hidden = false;

        } else if (crosshair_hidden == false) {
            // Show the crosshair
            SendToConsole("crosshair 1");
            printl("crosshair shown!")
            crosshair_hidden = true;

        }
    }

    function CrosshairAlpha(Add) {
        // cl_crosshairalpha
    }
} 

when i open the game and run the script, inside the games console it says

AN ERROR HAS OCCURED [the index 'crosshair_generator' does not exist]

CALLSTACK
*FUNCTION [main()] InputRunScript line [1]

LOCALS
[this] TABLE
 Entity script_crosshair encountered an error in RunScript()

If i define the crosshair_hidden variable inside the hideCrosshair() function crosshair_hidden = false; then every time i call the function it's value would be false. i need it to be defined outside the function, so that the variable can be accessed by other functions like CrosshairAlpha(), and so the variable value is not the exact same every time i call the function.

So how do you define a variable in a class in JavaScript, then pass that variable into a function?


Solution

  • You can initialize the properties in the construct method and refer to them later using this:

    class crosshair_generator {
        // Initialize
        constructor(crosshair_hidden = false) {
            this.crosshair_hidden = crosshair_hidden;
        }
    
        hideCrosshair() {
            if (this.crosshair_hidden == true) {
                // Hide the crosshair 
                SendToConsole("crosshair 0");
                printl("crosshair hidden!");
                this.crosshair_hidden = false;
    
            } else if(this.crosshair_hidden == false) {
                // Show the crosshair
                SendToConsole("crosshair 1");
                printl("crosshair shown!")
                this.crosshair_hidden = true;
    
            }
        }
    
        CrosshairAlpha(Add) {
            // cl_crosshairalpha
        }
    }