Lua Programming/variable

From Wikibooks, open books for an open world
Jump to navigation Jump to search

A variable is a symbolic name associated with a value. A variable acts as a container and the value it contains may be changed from within a running program, enabling data manipulation to take place from within the program.

Variables are dynamically typed.[edit | edit source]

In lua variables are dynamically typed, so no explicit typecasting is necessary.

Variables do not need predefinition prior to use[edit | edit source]

In lua, there is no need to declare or initialize variables before they are used. By default, variables are initialized to the value of nil.

Variable names[edit | edit source]

As in most programming languages, the name of a variable must be a sequence of letters, digits, or underscore symbols, and may not begin with a digit. The Lua interpreter is lettercase sensitive so variables with uppercase and lowercase names are distinct and separate from each other. It is not permissible to use keywords as variable names.

Variables do not need a sigil[edit | edit source]

Variables in lua are referenced by name only and are dynamically typed, so a sigil is not required when a variable is referenced.

Variables are global by default[edit | edit source]

In lua, variables are global by default, unless they are declared as local via a qualifier.

Variable names inside string constants are not expanded in Lua[edit | edit source]

The lua interpreter does not expand variables inside string constants. This means that "hello username" is always interpreted as constant string, even if username is a the name of a variable. Instead of using interpolation, new strings are constructed from string constants and variables, using concatenation operators.

Local variables have lexical scope[edit | edit source]

In lua, local variables have lexical scope and are visible to functions defined inside the variable scope.

Global variables are stored in environment tables[edit | edit source]

In lua, global variables are stored as fields in environment tables.