A variable is a name given to a storage area that our programs can manipulate. It can hold different types of values including functions and tables.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Lua is case-sensitive. There are eight basic types of values in Lua −
In Lua, though we don't have variable data types, we have three types based on the scope of the variable.
Global variables − All variables are considered global unless explicitly declared as a local.
Local variables − When the type is specified as local for a variable then its scope is limited with the functions inside their scope.
Table fields − This is a special type of variable that can hold anything except nil including functions.
A variable definition means to tell the interpreter where and how much to create the storage for the variable. A variable definition have an optional type and contains a list of one or more variables of that type as follows −
type variable_list;
Here, type is optionally local or type specified making it global, and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −
local i, j
local i
local a,c
The line local i, j both declares and defines the variables i and j; which instructs the interpreter to create variables named i, j and limits the scope to be local.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:
type variable_list = value_list;
Some examples are
local d , f = 5 ,10 --declaration of d and f as local variables.
d , f = 5, 10; --declaration of d and f as global variables.
d, f = 10 --[[declaration of d and f as global variables. Here value of f is nil --]]
jkdsd