2.3.4 Local variables

You can define a local variable by using a let declaration. Unlike module variables, local variables are established dynamically, and they have lexical scope. During its lifetime, a local variable shadows any module variable, module constant, or existing local variable with the same name.

Local variables are scoped within the smallest body that surrounds them. You can use let anywhere within a body, rather than just at the beginning; the local variable is declared starting at its definition, and continuing to the end of the smallest body that surrounds the definition.

A body is a region of program code that delimits the scope of all local variables declared inside the body. When you are defining functions, usually there is an implicit body available. For example, define method creates an implicit body. (For information about method definitions, see Section 3.1, page 27.) Other control structures, such as if, create implicit bodies. Bodies can be nested. If there is no body handy, or if you want to create a body smaller than the implicit one, you can create a body by using begin to start it and end to finish it:

? begin
    let radius = 5;
    let circumference = 2 * $pi * radius;
    circumference;
  end;
31.4159

The local variables radius and circumference are declared, initialized, and used within the body. The value returned by the body is the value of the expression executed last in the body, which is circumference. Outside the lexical scope of the body, the local variables are no longer declared, and trying to access them is an error:

? radius
ERROR: The variable radius is undefined.