Skip to main content

Variable Types

In LemonScript, you can also set a type for a variable. Setting a type is good because it won't allow for type errors anywhere in your program and often prevents variables from changing types, which further defends against unintended errors. Setting a type for a variable means that the variable's type can not be changed. To set a type of a variable, you can use this syntax when declaring it:

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

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.

For the type, it can be either Any, Number, String, Boolean or Null. If there is no type passed in, the type is automatically set to Any. This allows it to change to any value. You can still use this syntax with const, but it is not needed as the variable's value cannot be changed.

Here is an example demonstrating types of a variable:

var num: Number = 5
print(num) # 5
num = "string" # Error

When assigning a string to the num variable, it will error because num's type is a variable.

You can also set multiple types to a variable by using the | symbol with the following syntax:

var [variable name]: [type1] | [type2] ... = [value]

If we use the example above, but change its type to Number | String, the code will not error anymore, because the variable's value can be both a string or a number.

var num: Number | String = 5
print(num) # 5
num = "string" # No error