Variables
Variables
Values
Variables are named slots for storing values. You define a new variable in Jingle using a var
statement, like so:
This declares a new variable a
in the current scope and initializes it with the result of the expression following the =
. Once a variable has been defined, it can be accessed by name as you would expect.
Scope
Jingle has block scope: a variable only exists from where it is define to the end of the block.
Variables defined at the top level of a script are top-level and are visible to the module system. All other variables are local. Declaring a variable in an inner scope with the same name as an outer one is called shadowing and is not an error (although it’s not something you likely intend to do much).
However, declaring multiple variables of the same name in the same scope is an error.
Assignment
After a variable has been declared, the value can be reassigned using =
:
It’s an error to assign to a variable that isn’t defined. This can only be done with variables and binds.
Variable Types
Variables
Variables are dynamically-typed, inferred and mutable. This means you do not have to give it a type, and it can change along with the value of the variable. They are declared with the var
keyword.
Constants
Constants are statically-typed, inferred and immutable. This means you do not have to give it a type, but it cannot change. The value of the variable cannot change. They are declared with the const
keyword.
Typed Variables
Typed Variables are statically-typed, inferred and mutable. This means you do not have to give it a type, but it cannot change. The value of the variable cannot change. They are declared with the let
keyword.
Type Declarations
Types can be deliberately declared using type declarations. They are done like this:
You can declare the type of a variable multiple times:
These can be used for variables if you plan on changing the type of a variable rarely, but still multiple times. If you don't plan on changing the type than just use a typed variable. You can use bool
,int
,float/flt
,string/str
,any
in type declarations.
Last updated