Skip to main content

Variables

In LemonScript, there are two different types of variables, constant, and mutable. A constant variable, as the name describes, is constant and immutable. So the interpreter will throw an error if you try to change the value. The other type is mutable. This variable's value can be changed. To declare a variable, you can use the var or const keyword with this syntax:

[var | const] [variable name]

or

[var | const] [variable name] = [variable value]

The keyword is either var or const. Var is for a mutable variable, and const is for immutable and constant. The variable name has to start with an alphabetical letter or an underscore, then can be any character. It cannot contain spaces.

The value can be an expression, value, or even another variable. For example a number or a string. Without the value, the variable's value is automatically set to null.

Something to keep in mind when using variables is the scope. A variable is only avaliable in the scope, and cannot be accessed outside it. For example:

var a = 5if (a > 3) {    print(a)    var b = 12}print(b) # Error

The print(b) line will throw an error, because the variable b is only avaliable inside the if statement scope.

Constant variable immutability in more detail#

Here is an example of how a constant variable works:

const a = 5print(a) # 5
const b = a * 2print(b) # 10
a = 12 # This will error because 'a' is a constant variable

Assignment#

Assignment is when you change a variable's value to something else. For example:

var x = 10print(x) # 10x = 15print(x) # 15

Because x is already defined in the scope, you can change the variable's value to something else. You can also reference the variable's value inside the assignment. For example:

var a = 5print(a) # 5a = a * 2print(a) # 10

The assignment changes a's value to 10, because it is doubling the existing value.