luamoonscript

Moonscript static fields


I want to make class like that:

class Example
  field: false --some field shared for all instances of the class
  init: (using field) ->
    field = true --want to change value of the static field above

But in lua I got:

<...>
field = false,
init = function()
  local field = true //Different scopes of variable field
end
<...>

In docs I read that writing using helps to deal with it


Solution

  • You can change the value as you described by editing the metatable from the instance:

    class Example
      field: false
      init: ->
        getmetatable(@).field = true
    

    I don't recommend doing that, class fields are probably what you want to use:

    class Example
      @field: false
      init: ->
        @@field = true
    

    When assigning a class field you can prefix with @ to create a class variable. In the context of a method, @@ must be used to refernece the class, since @ represents the instance. Here's a brief overview of how @ works:

    class Example
      -- in this scope @ is equal to the class object, Example
      print @
    
      init: =>
        -- in this score @ is equal to the instance
        print @
    
        -- so to access the class object, we can use the shortcut @@ which
        -- stands for @__class
        pirnt @@
    

    Also, your use of using is incorrect. field is not a local variable. It's a field on the classes's instance meta table.