aboutsummaryrefslogtreecommitdiff
path: root/dynroute.tcl
blob: 2309ac74fe2489572d0402ef9850eff79c89e3c0 (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
package require Tclpd 0.2.1
package require TclpdLib 0.17

# dynroute: dynamically route messages based on first element
# non-matching arguments are sent to last inlet
# constructor: <float>   specify the number of outlets (default: 1)
# send commands to the right inlet
# available commands:
# add <atom> <float>     route selector <atom> to output number <float>
# remove <atom> <float>  remove previously created routing
# clear

pd::class dynroute {
    constructor {
        pd::add_inlet $self list

        set @num_outlets [pd::arg 0 int]
        if {$@num_outlets < 0} {set @num_outlets 2}

        for {set i 0} {$i < $@num_outlets} {incr i} {
            pd::add_outlet $self list
        }

        set @routing {}
    }

    0_list {
        set sel [pd::arg 0 any]
        set out [expr {$@num_outlets-1}]
        catch {set out [dict get $@routing $sel]}
        pd::outlet $self $out list $args
    }

    1_add {
        set sel [pd::arg 0 any]
        set out [pd::arg 1 int]
        if {$out < 0 || $out >= $@num_outlets} {
            pd::post "error: add: outlet number out of range"
            return
        }
        dict set @routing $sel $out
    }

    1_remove {
        set sel [pd::arg 0 any]
        set out [pd::arg 1 int]
        if {$out < 0 || $out >= $@num_outlets} {
            pd::post "error: add: outlet number out of range"
            return
        }
        catch {dict unset @routing $sel $out}
    }

    1_clear {
        set @routing {}
    }
}