Local Variables

This topic is meant to document local variables in Pile

Overview

In Pile, a local variable is a value bound to a name at runtime. When used, its stored value is pushed on the stack.

A local variable can:

  • Be destroyed. Its name becomes undefined after the end of a scoped block.
  • Be overwritten.

Defining Local Variables

To define a local variable in Pile, use the as..let statement block.

Use the as keyword followed by the names of the variables you want to define, separated by space.

Then write let and put the code that uses those variables inside the block

NOTE: as..let statement needs values on top of the stack to bind. If there's no value or too few of them, you'll see an Unbound Variable error.

Syntax:

as <NAMES...> let
<CODE>
end

Code examples

Here's an example demonstrating a numbers being assigned to different variables:

1 2 3 4
as a b c d let
# Each variable is assigned to each corresponding value
# a = 1, b = 2, c = 3, d = 4
end
# After this end, a, b, c, and d are not valid variables anymore

Here's another example showing how variables can be used in procedures to work as named arguments:

proc square
as number let
number dup *
end
end

8 square println
# Output: 64

In this example, the variable number is not valid after the call of square which is (in most cases) the desired behavior for named arguments.