aboutsummaryrefslogtreecommitdiffstats
path: root/lib/util.moon
blob: af5d8f8d596b6d635f091fa89dc344e69f9da207 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import Const, Op from require 'core'

class switch_ extends Op
  @doc: "(switch i v0 [v1 v2...]) - switch between multiple inputs

when i is true, the first value is reproduced.
when i is false, the second value is reproduced.
when i is a num, it is (floor)ed and the matching argument (starting from 0) is reproduced."

  setup: (@i, ...) =>
    @choices = { ... }

  update: (dt) =>
    @i\update dt
    i = @i\get!

    for choice in *@choices
      choice\update dt

    active = switch @i\get!
      when true
        @choices[1]
      when false
        @choices[2]
      else
        i = 1 + (math.floor i) % #@choices
        @choices[i]
    @value = active and active\get!

class switch_pause extends Op
  @doc: "(switch- i v0 [v1 v2...]) - switch and pause multiple inputs

like (switch ...) except that the unused inputs are paused."

  setup: (@i, ...) =>
    @choices = { ... }

  update: (dt) =>
    @i\update dt
    i = @i\get!
    active = switch @i\get!
      when true
        @choices[1]
      when false
        @choices[2]
      else
        i = 1 + (math.floor i) % #@choices
        @choices[i]

    @value = if active
      active\update dt
      active\get!

class edge extends Op
  setup: (@i) =>
    @value = false
    @last = false

  update: (dt) =>
    @i\update dt

    now = @i\get!

    @value = not @last and now
    @last = now

class keep extends Op
  @doc: "(keep value [default]) - keep the last non-nil value

always reproduces the last non-nil value the input produced or default.
default defaults to zero."

  setup: (@i, @default=Const.num 0) =>

  update: (dt) =>
    @i\update dt

    next = @i\get!
    @value = next or @value or @default\get!

{
  'switch': switch_
  'switch-': switch_pause
  :edge
  :keep
}