Cabbage Logo
Back to Cabbage Site

Why does K-rate variable hit every branch in an if statement?

I am trying to use an envelope to modulate a parameter that is passed through an if statement.
The issue is that if I use a k-rate variable it hits every branch of the if statement, but I need to modulate this using an envelope which is k-rate.

First I would like to know why my k rate variable is hitting every branch, and then how I would go about modulating it with an envelope but only hitting the appropriate branch?

kEnv madsr 0.01, 0.01, 0.9, 0.2

kSlider = chnget:k("slider") * kEnv

prints("SLIDER VALUE: %f\n", kSlider)

        if (kSlider <= 1) then  
            prints("Less Than 1\n")

        elseif (kSlider <= 2) then
            prints("Less Than 2\n")

        elseif (kSlider <= 3) then
            prints("Less Than 3\n")
            
        endif

My output from the above code

SLIDER VALUE: 0.000000
Less Than 1
Less Than 2
Less Than 3

The prints opcode prints at i-time. Try printks instead…

1 Like

Ok, wow well that seemed to work, but something still doesn’t quite make sense to me.

If I amend the code as follows, it still prints every branch.

kSlider = 1

prints("SLIDER VALUE: %f\n", kSlider)

        if (kSlider <= 1) then  
            prints("Less Than 1\n")

        elseif (kSlider <= 2) then
            prints("Less Than 2\n")

        elseif (kSlider <= 3) then
            prints("Less Than 3\n")
            
        endif

Should kSlider not always be =1? Why does the update time matter?

The print family of opcodes works at different rates which can lead to some serious confusion! Doing something like:

 if (kSlider <= 1) then  
            prints("Less Than 1\n")

makes little sense, as your are doing a k-time check, but using an i-time opcode to print “less than 1”. Try the following, it uses the k-rate version of prints, printks. It uses a slow envelope, which I multiple by 2, so you should see when each branch gets hit.

 kEnv madsr 2, 0.01, 0.9, 0.2

    kSlider = 2 * kEnv

    printks("SLIDER VALUE: %f\n", .5, kSlider)

    if (kSlider <= 1) then  
        printks("Less Than 1\n", .5)

    elseif (kSlider <= 2) then
        printks("Less Than 2\n", .5)

    elseif (kSlider <= 3) then
        printks("Less Than 3\n", .5)
            
    endif
1 Like

Ok that makes more sense, thanks again Rory :slightly_smiling_face: