Trainerflow Docs trainerflow.com
Commands › If

Commands

If

Run commands only when a condition is met, and choose between alternatives with else and the ternary operator.

Purpose

The If command is one of those commands that add smarts to your program. Its purpose is to choose which commands the program runs, based on some condition.

The typical use case is that you want to run a bunch of commands only when some expression is true. So, for example, if you want the athlete to run an additional mile if they finished the previous run in under 35 minutes, then you need an if.

Definition

An if command is the keyword if, a test expression and the commands to run when the test passes, in curly braces:

action Run [title: "Run"]
output:|mi| distance [title: "Distance"]
input:|min| duration [title: "Time"]

exec run(miles) {
    specify:Run distance miles
    measure duration
}

let last = run(3|mi|)
if (last.duration < 35|min|) {
    run(1|mi|)
}

The parentheses around the test expression are optional, but they make the condition easier to spot.

Else

You can add an else with the commands to run when the test fails, and chain as many else if as you need in between:

action BackSquat [title: "Back squat"]
output:number reps [title: "Reps"]
output:|kg| weight [title: "Weight"]
input:number rpe [title: "RPE"]

exec squat(load) {
    specify:BackSquat reps 5, weight load
    measure rpe
}

let load = 100|kg|
let set = squat(load)
if (set.rpe >= 9) {
    load = load - 5|kg|
} else if (set.rpe <= 7) {
    load = load + 5|kg|
} else {
    load = load + 2.5|kg|
}
squat(load)

Execution

The if command starts by calculating its test expression. If the result is true (anything other than false or nil), it runs the commands that follow it. Otherwise it moves to the next else if, if there is any, and repeats the calculation of its test expression. It does the above until it finds the first test expression that is true and runs its commands. If it doesn’t find one, it runs the commands of the else, if there is one. After that, the program continues with the command after the if.

Note that only the first matching branch runs, even if later tests would also be true. In the example above an RPE of 6 matches <= 7 and nothing else.

The ternary operator

When all you need is to pick between two values, rather than two sets of commands, use the ternary operator test ? value : otherwise:

import "coach/common/rest.cl"

let day = 3
rest(day == 3 ? 3|day| : 2|day|)

It reads exactly like the if: if day == 3 the value is 3|day|, otherwise 2|day|.