Variables and Scope
Understand variables and the scoping system in Pile
Variables
In Pile, a 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 (have its value changed during runtime).
Defining and using variables
There are two ways to define variables in Pile, you can use the more compact let
statement, or you may use the as-let
statement to define multiple variables.
Using let
statement
# Use let <name> syntax to define variables
# Remember to be sure that you have at least a value on the stack
# or you will get a Stack Underflow error
69 let x
# Now, to use it, just refer to its name and its value will be pushed onto the stack:
x println # Result: 69
Using as-let
statement
as-let
statement is a way I found to make defining multiple variables easier through the logic of a program.
Use the as
keyword followed by the names of the variables you want to define, separated by space.
69 420 1336 as variable1 variable2 variable3 let
# Note that the binding order is related to how they appear reading, not the order on the top of the stack.
# That means variable1 = 69, variable2 = 420, and variable3 = 1336
Scoping
In Pile, scoping works pretty much like any other programming language. All variables defined inside a scope are invalidated after the end of the same.
The following structures in Pile generate scoped blocks:
- Modules
- Procedure blocks
Other blocks like conditionals and loops do not create scoped blocks. This is purely a design choice.
Code examples
Here's another example, this time showing how as-let
can be used in procedures to work as named arguments:
proc square as number let
number dup *
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.