Local variables

Local variables efficiently store values of any type. Within the scope of a rule or a function, you can use them 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 the following example, the Lot rule that was introduced in the previous section, CGA functions, is extended:

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 more information about the comp operation). If the height value is less than 35, the roof angle is set to 45 degrees; otherwise, it is set to 10 degrees. You 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, you 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

In addition to rules, you can also define local variables 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

You can define a sequence of local variables. An expression may reference a local variable that was defined previously in the list. This makes local variables a 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