github.com/lab47/exprcore@v0.0.0-20210525052339-fb7d6bd9331e/exprcore/testdata/control.star (about) 1 # Tests of Starlark control flow 2 3 load("assert.star", "assert") 4 5 def controlflow() { 6 # elif 7 x = 0 8 if True { 9 x=1 10 } elif False { 11 assert.fail("else of true") 12 } else { 13 assert.fail("else of else of true") 14 } 15 assert.true(x) 16 17 x = 0 18 if False { 19 assert.fail("then of false") 20 } elif True { 21 x = 1 22 } else { 23 assert.fail("else of true") 24 } 25 assert.true(x) 26 27 x = 0 28 if False { 29 assert.fail("then of false") 30 } elif False { 31 assert.fail("then of false") 32 } else { 33 x = 1 34 } 35 assert.true(x) 36 } 37 controlflow() 38 39 def loops() { 40 y = "" 41 for x in [1, 2, 3, 4, 5] { 42 if x == 2 { 43 continue 44 } 45 if x == 4 { 46 break 47 } 48 y = y + str(x) 49 } 50 return y 51 } 52 assert.eq(loops(), "13") 53 54 # return 55 g = 123 56 def f(x) { 57 for g in (1, 2, 3) { 58 if g == x { 59 return g 60 } 61 } 62 } 63 assert.eq(f(2), 2) 64 assert.eq(f(4), None) # falling off end => return None 65 assert.eq(g, 123) # unchanged by local use of g in function 66 67 # infinite sequences 68 def fib(n) { 69 seq = [] 70 for x in fibonacci { # fibonacci is an infinite iterable defined in eval_test.go 71 if len(seq) == n { 72 break 73 } 74 seq.append(x) 75 } 76 return seq 77 } 78 assert.eq(fib(10), [0, 1, 1, 2, 3, 5, 8, 13, 21, 34])