go.starlark.net@v0.0.0-20231101134539-556fd59b42f6/starlark/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    assert.true(x)
    15  
    16    x = 0
    17    if False:
    18      assert.fail("then of false")
    19    elif True:
    20      x = 1
    21    else:
    22      assert.fail("else of true")
    23    assert.true(x)
    24  
    25    x = 0
    26    if False:
    27      assert.fail("then of false")
    28    elif False:
    29      assert.fail("then of false")
    30    else:
    31      x = 1
    32    assert.true(x)
    33  controlflow()
    34  
    35  def loops():
    36    y = ""
    37    for x in [1, 2, 3, 4, 5]:
    38      if x == 2:
    39        continue
    40      if x == 4:
    41        break
    42      y = y + str(x)
    43    return y
    44  assert.eq(loops(), "13")
    45  
    46  # return
    47  g = 123
    48  def f(x):
    49    for g in (1, 2, 3):
    50      if g == x:
    51        return g
    52  assert.eq(f(2), 2)
    53  assert.eq(f(4), None) # falling off end => return None
    54  assert.eq(g, 123) # unchanged by local use of g in function
    55  
    56  # infinite sequences
    57  def fib(n):
    58    seq = []
    59    for x in fibonacci: # fibonacci is an infinite iterable defined in eval_test.go
    60      if len(seq) == n:
    61        break
    62      seq.append(x)
    63    return seq
    64  assert.eq(fib(10),  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34])