'Global' Enum

I’d like to use an enum (I think!) to represent a game state which is available to various classes (files) like this:

enum State {
    HIDING;
    SEEKING;
}

Am I right in thinking this has to be declared outside of any class and is therefore only accessible in the file in which it is declared? I can’t seem to make it work any other way.

1 Like

enum is just a set of values, you later can assign one of its values to a variable:

About global state, just use static property as in my example.

Thanks for the reply. But doesn’t that set up mean that the value of the static variable ‘state’ can only changed within that class? I I have a class Test2 in another file it wouldn’t know about the enum so how could code in that class change the state?

You can change the static variable wherever you want.

Sorry if I’m being dense but that doesn’t seem to work if class Test2 is in a different file.

‘Type not found : State’

The static var in Test2 class is public?

Test.hx:

class Test {
    public static var state = State.HIDING;
    
    static function main() {
        trace(Test.state);
        Test2.seek();
        trace(Test.state);
        Test2.hide();
        trace(Test.state);
    }
}

enum State {
    HIDING;
    SEEKING;
}

Test2.hx:

class Test2 {  
    public static function hide() {
        Test.state = State.HIDING;
    }
    
    public static function seek() {
        Test.state = State.SEEKING;
    }
}

Test2.hx:7: characters 21-26 : Type not found : State
Test2.hx:3: characters 21-26 : Type not found : State

Admittedly I wouldn’t be calling functions in Test2 from Test to set the state but I might want to change the state within some other function in Test2, eg if Test2 handled the game menu I might want to change the game state from one of its methods.

1 Like

import Test.State;

Test is a module which has class Test (yeah) and enum State inside it. This is actually pretty funny, because

import Test.State; // Test is a module Test, you are importing enum
import Test.state; // Test is a class Test, you are importing static field

That’s why you can do Test.State.HIDING but not typedef X = Test; X.State.HIDING. Module level function may solve this kind of … thing. But maybe not.

1 Like

Ah I see, thanks to you both for the help.

As Test is the main class I hadn’t considered it could be treated as a module and therefore any part of it imported into Test2.