0

In MoonScript, what is the difference between these types field declarations?:

class SomeClass
     a : {}
    @b : {}
     c = {}
    @d = {}
Dess
  • 2,064
  • 19
  • 35

1 Answers1

0

a: {} creates a in the base class and is available per instance.
https://moonscript.org/reference/#the-language/table-literals

If the value is a table, a: {} will create it only once. To actually have unique tables, you will need to create it in the constructor (and thus set it in the instance): https://moonscript.org/reference/#the-language/object-oriented-programming

@b: {} creates b in the class object and is "shared".
https://moonscript.org/reference/#the-language/object-oriented-programming/class-variables

c = {} is a class declaration statement, it is a local variable available during class declaration. With self you have access to the class.

@d = {} is a class declaration statement, but due to the @ prefix it's stored in the class.
https://moonscript.org/reference/#the-language/object-oriented-programming/class-declaration-statements

Paste your code in https://moonscript.org/compiler/ to see all this in action.

Luke100000
  • 1,395
  • 2
  • 6
  • 18
  • `a: {}` seems to be shared amongst the instances; not per instance. In fact, they all seem to be. Seems like the only way to create instance vars is within fat arrow functions, by using @varname – Dess Apr 15 '23 at 09:06
  • True, you will have to overwrite the property once to avoid using the base class value, similar as in https://moonscript.org/reference/#the-language/object-oriented-programming I fixed the answer. I have to admit, I never used moonscript and I may miss more convenient ways to do that. – Luke100000 Apr 15 '23 at 09:22
  • I also didn't find an actual difference between `@a:` and `@a=`, since the compiler doesn't complain when re declaring a property anyways. It compiles to the same code. – Luke100000 Apr 15 '23 at 09:32