Search code examples
static-variablescrystal-lang

Crystal static variables


Has Crystal got static variables or must I use global variables with a file / global scope ?

def test(value)
  static var = 1
  var += value
  return var
end

pp test 0 #=> 1
pp test 1 #=> 2
pp test 1 #=> 3
pp test 0 #=> 3

Solution

  • Crystal has no static variables scoped to methods. You'll need to use class variables for this:

    class Test
      @@var = 1
      def self.test(value)
        @@var += value
        return @@var
      end
    end
    
    pp Test.test 0 #=> 1
    pp Test.test 1 #=> 2
    pp Test.test 1 #=> 3
    pp Test.test 0 #=> 3
    

    Also you can use macros class_property, class_setter or class_getter

    class Test
      class_property var = 1
    end
    
    Test.var += 0
    pp Test.var #=> 1
    Test.var += 1
    pp Test.var #=> 2
    Test.var += 1
    pp Test.var #=> 3
    Test.var += 0
    pp Test.var #=> 3