4

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; }

2 Answers2

4

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

Artyom Shalkhakov
  • 1,101
  • 7
  • 14
0

You can also use the extvar feature to update an external global variable (declared in the target language). This is very useful if you compile ATS to a language that does not support explicit pointers (e.g., JavaScript). Here is a running example that makes use of this feature:

http://www.ats-lang.org/SERVER/MYCODE/Patsoptaas_serve.php?mycode_url=http://pastebin.com/raw/MsXhVE0A

Hongwei Xi
  • 895
  • 1
  • 5
  • 10