Local variables efficiently store values of any type. Within the scope of a rule or a function they can be used many times via an identifier in the same way as parameters. Local variables eliminate the need to pass intermediate results as a parameter and help you to better structure your code.
Example 1
In this example we extend the rule Lot introduced in the previous section CGA functions.
getHeight(area) =
case area > 1000 : 300
case area > 500 :
20% : 200
50% : 150
else : 100
else : rand(20,50)
Lot -->
Lot(getHeight(geometry.area))
Lot(height) -->
extrude(height)
comp(f) { top : roofHip(case height < 35 : 45 else : 10) Roof
| all = Envelope }
A roof is constructed on the top face of the extruded geometry (see Component split for details about the comp operation). If the height is less than 35 the roof angle is set to 45 degrees, otherwise it is set to 10 degrees. We want to call the function getHeight() only once and use the evaluated value many times. This is achieved by passing the computed height value as a parameter to an overloaded Lot rule (see Rule with parameters).
With local variables we can write this using only one rule Lot:
Lot with ( height := getHeight(geometry.area) ) -->
extrude(height)
comp(f) { top : roofHip(case height < 30 : 45 else : 10) Roof
| all = Envelope }
The local variable height is evaluated and stored as soon as the rule is invoked. It is not reevaluated when it is referenced within the definition of the rule.
Example 2
Beside rules, local variables can also be defined for functions, const functions and attributes. In the following example the getHeight() function has no parameter area. Instead, the area is computed and stored in a local variable as soon as the function is called.
getHeight with ( area := geometry.area ) =
case area > 1000 : 300
case area > 500 :
20% : 200
50% : 150
else : 100
else : rand(20,50)
Example 3
A sequence of local variables can be defined. An expression may reference a local variable which was defined prior in the list. This makes local variables an easy tool to split complex calculations into a few smaller steps.
getHeight with (
area := geometry.area
minHeight := sqrt(area) * 0.2
heightDowntown := 80%: rand(15,35) else: rand(5,15)
heightHighrise := rand(50,150)
height := 10%: heightHighrise else: heightDowntown
finalHeight := max(minHeight, height)
) = finalHeight