Variables

From MiniScript Wiki
Revision as of 13:30, 3 June 2020 by JoeStrout (talk | contribs) (Created page with "A ''variable'' is a word (also called an identifier) associated with a value. Think of variables as little boxes that you can store data in. You create a variable simply by as...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

A variable is a word (also called an identifier) associated with a value. Think of variables as little boxes that you can store data in. You create a variable simply by assigning a value to it:

x = 42

This line creates a variable called x, if it didn’t exist already, and stores 42 in it. This replaces the previous value of x, if any.

Variables in MiniScript are dynamically typed; that is, you can assign any type of data to any variable.

Variables are always local in scope. That means that a variable called x inside one function has nothing at all to do with another variable called x in another function; each variable is scoped (restricted) to the current function executing at the time of the assignment.

However, MiniScript also supports code outside of any function. In this context, local and global variables are the same. In other words, assigning 42 to x outside of a function creates a global variable called x. Such global variables may be accessed from any context.

Note that when a context has a local variable of the same name as a global, an identifier will always resolve to the local variable first. Similarly, a simple assignment statement within a function will always create a local variable, rather than a global one. In cases where you really need to access the global variable instead, there is a globals object that provides this access. (There is also locals but this is rarely needed, since simple references always access locals anyway.)

Example

demo = function()
    print x          // prints the global x (40)
    x = 2            // creates a local ‘x’ with a value of 2
    print x          // prints the local x (2)
    print globals.x  // prints the global x again (40)
    globals.x = 42   // reassigns the global x
    print x          // still the local value (2)
    print globals.x  // prints the new global value (42)
end function
x = 40   // creates a global ‘x’ with a value of 40
demo     // invokes the function above

Overuse of global variables can sometimes lead to tricky bugs, so it’s best to use them sparingly and rely on local variables as much as possible. MiniScript is designed so that this good practice is what happens naturally.