Variables

Variables are commonly declared using the var keyword:

var num = 42
var str = "42"
var bool = true

Lexical variables

These kinds of variables are lexical, but statically block scoped. This is the usual way of declaring variables in Sidef.

var x = 42    # sets the lexical x to 42
say x         # prints the lexical value of x

Static variables

This kind of variables are static, block-scoped and initialized only once.

static x = 42   # sets the static x to 42
say x           # prints the static value of x

Global variables

Global variables are declared at the top-level of the current namespace. They can be accessed from everywhere, anytime. However, try to avoid using them, unless you really don't have any better alternative.

global x = 42     # sets global x to 42
say x             # prints the global value of x

Local variables

Local variables (also known as "dynamically scoped variables") can be used to localize array/hash lvalues or global variables to a limited scope.

A slightly more advanced example, illustrating the localization of an hash lvalue, would be:

Variable scoping

All variables (including functions and classes) are block scoped in the following way:

Declaring multiple variables at once is also possible:

We can, also, declare variables with some default values:

Slurpy variables

Slurpy (or greedy) variables are a special type of variables which can be initialized with a list of values, creating automatically a container to hold the data.

Working with variables

Any method applied to a variable is applied on the object at which the variable is pointing at:

Special ! at the end of a method changes the variable in-place (almost like in Ruby):

Appending the = sign at the end of arithmetic operators, the variable will be changed in place:

The special operator := (also available as \\=), assigns a value to a variable if the current value of the variable is nil:

The defined-or operator \\ can be used for checking if a variable is defined or not:

Special identitiers

  • ARGV is an Array that contains the program's command-line arguments, that were not given to Sidef.

  • ENV is an Hash copy of environment variables and their values when the program was started.

  • ARGF is a FileHandle object used to read lines from argument-files or from STDIN when no argument has been specified.

  • DATA is a FileHandle object that points to the data stored after the __END__ or __DATA__ tokens.

Topic variable

The special topic variable (_) is declared at compile-time in each block-object in the program. You may not see its real name very often, because it has been overtaken by the elegant prefix dot (.) operator:

...where .sqrt really means _.sqrt, and .log.say means _.log.say.

Last updated