Game Development Reference
In-Depth Information
Code Blocks and Scopes
In Lua, every variable has a scope, which means that it is accessible to the code depending on its
life cycle as determined by the scope. Variables are either global or local . By default, variables are
defined as global unless explicitly defined as local.
In code, variables set between a do and an end block are not accessible outside of the block, and
any local variables that are set outside of the block are accessible inside the block.
Let us look at this with an example:
i = 1
print("i = ", i)
local i = 2
print("i = ", i)
is a simple term given to the process of converting a string into a number following the
-- 3 is printed
In many languages, attempting such an arithmetic operation between two different data types (in this
case a string and a number) would fail. In some other scripting languages, this code would instead
add the value to the string, resulting in the string "12" . However, in Lua, this outputs the value 3 ,
where one is converted into numeric 1 and then added to the value of two to output 3 .
However, if we wanted to add the two strings "1" and "2" to get "12" , then we would need to
use what is called concatenation . In Lua the concatenation operator is the double-dot ( .. ). This
combines the two strings and returns a new string that contains the two strings passed.
Lua Operators
The operators in Lua can be grouped into different types of operators, which include arithmetic, relational,
and logical operators, among others.
Arithmetic Operators
These do not need much of an introduction; they are simple and straightforward. Table 1-1 lists them.
 
Search WWH ::




Custom Search