Cobra/Hops.cobra

Материал из Викиучебника — открытых книг для открытого мира
Перейти к навигации Перейти к поиску
"""
Example DocString for a module.

This program doesnt do anything useful or realistic beyond being an example of
a cobra program and showing some of the language constructs.
"""

#Assembly attributes
assembly has SharedAttribute

use System.Text.RegularExpressions

%%number decimal

namespace Hops
    class Example
        var counter = 0
        
        def incCount(i as int)
            .counter += i
        
        def main is shared
            e = Example()
            e.incCount(10)
            assert e.counter == 10
            
    class AnotherExample
        pass
        
    struct Point
        var x = 0
        var y = 0
    
    enum ColorPart
        """What is the color of magic"""
        Red
        Green
        Blue
        Octarine
   
    sig VoidDelegate   # method taking no args and having no return type
    sig NullStringDelegate(s as String) as String? # method taking String and returning String or null

    extend String
        def fmt(args as vari Object) as String
            """
            Returns the string with any given args applied to it via String.Format
            """
            test
                s = '{0}is{1}'
                assert s.fmt('0', '1') =='0is1'
                assert s.fmt(2, 1) == '2is1'
                assert s.fmt('One', 'NotTwo') == 'OneisNotTwo'
                assert s.fmt(nil, nil) == 'is'
            body
                return String.format(this, args) to !.