Introduction to Lua Programming
Written By: S Kokila
- 31 Aug 2007 -
Description: Lua is a powerful, light-weight programming language designed for extending applications. Coupled with it being relatively fast and having a very lenient license, it has gained a following among game developers for providing a viable scripting interface. It has been used in games such as World of Warcraft and Far Cry, and in applications such as Adobe Photoshop Lightroom and Snort.
- What is Lua?
- Getting Started
- Identifiers, Types, and Values
- Variables and Expressions
- Operators
- Statements and Assignments
- Control Structures
- File I/O
Variables
There are 2 kinds of variables in Lua, global variables, and local variables.
A variable should be explicitly declared local, otherwise it is global. The local variables are lexically scoped and are accessible by the functions defined inside their scope. On the other hand, the global variable is available for use till the end of the program from the point where they are created.
The visibility rules for local and global variables can be easily understood from the example below:
x=5 -- Global Variable do -- Start of a block 1 local x=x -- Local Variable print (x) -- Prints 5 x=x+2 -- Modifies local x print (x) -- Prints 7 do -- Start of block 2 local x=x+4 -- Yet another local x :) print (x) -- prints 11 end -- End of block 2 print (x) -- Prints 7 end -- End of block 1 print (x) -- Prints 5, global variable
Notice that we assign the value of x in the previous block to the x in the next block. This is possible because the local variables can be freely accessed by the functions defined inside their scope. The local variable used by the inner function is called an upvalue or external local variable, inside the inner function.
Expressions
Expressions yield values. It includes the numeric and string constants (literals), variables, binary & unary operations, function definitions & calls, and table constructors.