Const within Class

Monkey Forums/Monkey Programming/Const within Class

erebel55(Posted 2014) [#1]
If I declare a const within a class does it create that const in memory for every instance of that class? Or does it only create it once in memory?

For example if I have the following and I create n coins from this, how many times is VALUE declared in memory?

Class Coin
    Const VALUE:Int = 10
End Class



SLotman(Posted 2014) [#2]
Constants are not created in memory - by definition once you compiled, their value is replaced in your code. For example:

Const VAL_X = 10
my_value = VAL_X * 2 ; this will be compiled as my_value = 10 * 2.

I don't know if Monkey uses this approach (probably not, it just leaves a 'const' in the target language as it should) - but once your game is compiled, you can bet constants won't require more memory.

If you want a variable, inside the class with only one instance, you can use something like:

Class Coin
Global VALUE:Int = 10
End Class

In this case, VALUE will be like a "static" var in the class - accessible as "Coin.VALUE", and it only uses sizeof(Int) in memory, no matter how many "new Coin()" you make.


erebel55(Posted 2014) [#3]
This is great, thank you SLotman :)


Goodlookinguy(Posted 2014) [#4]
@SLotman Monkey replaces constants with their values. It doesn't use const keywords or anything else to define them as that would be redundant.