Wiki

root/cobra/trunk/HowTo/101-WriteBasicSyntax.cobra

Revision 2335, 1.9 KB (checked in by Chuck.Esterbrook, 2 years ago)

Improvements to the How-To's.

  • Property svn:eol-style set to native
Line 
1"""
2This is a doc string for the whole module.
3"""
4
5
6class Person
7    """
8    This is a class declaration.
9    """
10
11    var _name as String  # declare an object variable. every instance of Person will have a name
12    var _age as int
13
14    cue init(name as String, age as int)
15        base.init
16        _name = name
17        _age = age
18
19    def sayHello
20        # This is a method
21
22        # In strings, anything in brackets ([]) is evaluated as an expression,
23        # converted to a string and substituted into the string:
24        print 'Hello. My name is [_name] and I am [_age].'
25
26    def add(i as int, j as int) as int
27        """ Adds the two arguments and returns their sum. """
28        return i + j
29
30
31class Program
32
33    def main
34        # Create an instance
35        p = Person('Bob', 30)
36
37        # Invoke a method
38        p.sayHello
39
40        # Invoke a method with arguments
41        print p.add(2, 2)
42
43        # Assert the truth of something
44        assert p.add(2, 2)==4
45
46        # If statement
47        a = 2
48        b = 1
49        if a > b
50            print 'a is greater'
51            print 'b is smaller'
52
53        # If-else statement
54        # See also: "Make An If Else Ladder" How To
55        if a > b
56            print 'a is greater'
57        else
58            print 'a is not greater'
59
60        # Can put target on same line if the target is just one statement
61        if a > b, print 'a is greater'
62        else, print 'b is greater or equal'
63
64        # While loop
65        while a > b
66            a -= 1  # augmented assignment
67       
68        # While loop in one line
69        while a > b, a -= 1
70
71        # Parallel assignment
72        a, b = 1, 2
73       
74        # Lists -- see the "Use Lists" How To for more info
75        t = ['a', 'b', 'c']
76        for letter in t, print letter
77
78        # Dictionaries
79        d = {'a': 1, 'b': 2}
80        assert d['a'] == 1 and d['b'] == 2
81        for key, value in d
82            print '[key] = [value]'  # string interpolation
83
84        # Sets -- like lists, but no repetition
85        letters = {'a', 'b', 'c'}
86        assert 'a' in letters
87        for letter in letters, print letter
88
89        # Line continuation is implicit with parenthesized arguments
90        p = Person('Bob',
91                    30)
92
93        # Line continuation can be done explicitly with an underscore
94        # The next line is indented the same or more
95        b = a *  _
96            10
Note: See TracBrowser for help on using the browser.