Changes between Version 12 and Version 13 of AllOfCobraInOnePage
- Timestamp:
- 01/10/14 06:23:11 (11 years ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
AllOfCobraInOnePage
v12 v13 44 44 45 45 examples: 46 ... 46 {{{ 47 #!cobra 48 interface IAudioPacket 49 def toWavPacket as WavPacket 50 51 52 class WavPacket implements IAudioPacket 53 cue init(bytes as uint8[]) 54 base.init 55 # ... create the wav packet format, using the bytes 56 57 def toWavPacket as WavPacket 58 return this 59 60 class Mp3Packet implements IAudioPacket 61 var bytes as uint8[] 62 def toWavPacket as WavPacket 63 wavBytes = Mp3Utils.decode(.bytes) 64 wavpack = WavPacket(wavBytes) 65 return wavpack 66 67 }}} 47 68 48 69 49 70 valid keywords inside a method (def): 50 71 you can have "trace, assert" wherever you want inside a method 51 very useful for debugging are 52 trace (also accepts multiple variables) 72 very useful for debugging are 'trace' and 'assert' 53 73 }}} 54 74 {{{ … … 64 84 assert accepts a boolean, with one expression per line. 65 85 example: 66 86 }}} 67 87 68 88 69 89 contracts example: 90 without contracts you might get surprising values, not knowing why 91 {{{ 92 #!cobra 70 93 def gap(a as uint, b as uint) as uint 94 test 95 assert .gap(7,9) == 2 71 96 require 72 0 <= a <= 1000, 0 <= b <= 1000 73 # a >= b # enable this line (or change to ints) to fix the definition 74 ensure 75 result <= 1000 97 0 <= a <= 1000 # in this way it's possible to constrain the valid range of arguments for this function. 98 0 <= b <= 1000 99 # a >= b # enable this line to find the error 100 101 ensure # we add ensure because we got unexpected results, and it failed. 102 result <= 1000 # the return value is assigned to the 'result' variable, so you can test it in the 'ensure' clause 76 103 body 77 104 res = a - b # is something wrong with this code? (when b > a, uint handles negatives by going to uint's maxvalue) 78 trace res 105 # a fix would be to check if a > b, a-b, else b-a 106 trace res # prints out the value and variable name, along with location in code. 79 107 80 return res 81 82 # without contracts you might get surprising values, not knowing why 108 return res 109 83 110 }}} 84 111 … … 86 113 mixin example: 87 114 {{{ 88 115 #!cobra 89 116 mixin VolumeSupport 90 117 pro volume from var as int … … 97 124 }}} 98 125 {{{ 126 #!cobra 99 127 class Radio adds VolumeSupport 100 128 cue init … … 104 132 }}} 105 133 {{{ 134 #!cobra 106 135 class TV adds VolumeSupport 107 136 cue init … … 110 139 }}} 111 140 {{{ 141 #!cobra 112 142 class Program 113 143 def main