Search code examples
ats

How to create a global variable in ATS?


Basically, I am looking for something more or less equivalent to the following C code:

int theGlobalCount = 0;

int
theGlobalCount_get() { return theGlobalCount; }

void
theGlobalCount_set(int n) { theGlobalCount = n; return; }

Solution

  • You could use a neat trick: declare a mutable global variable, and make a ref (aka mutable reference) point to it (no GC is required to make this work!). Then, implement functions to provide access to the mutable reference.

    local
    
    var theGlobalCount_var : int = 0
    val theGlobalCount = ref_make_viewptr (view@ theGlobalCount_var | addr@ theGlobalCount_var)
    
    in // in of [local]
    
    fun
    theGlobalCount_get () : int = ref_get_elt (theGlobalCount)
    
    fun
    theGlobalCount_set (n: int): void = ref_set_elt (theGlobalCount, n)
    
    end // end of [local]
    

    Note that declarations inside local-in are visible only to code inside in-end. Therefore, neither theGlobalCount_var nor theGlobalCount are visible outside the scope of the local.

    Full code: glot.io