Lua means Moon in Portuguese. Lua is fast, embeddable and lightweight scripting language. It was created in 1993 in Brazil.
This short tutorial on Lua is for programmers who have experience with 'C like' programming languages such as C, C++, Objective C and Java.
As in many scripting languages, in Lua variables don't have types. Only values have types. There are 8 value types in Lua: nil, boolean, number, string, table, function, thread and userdata. Out of these, following are used the most:
Though following are available, they are used only in special cases:
type functionThe type function gives the type of the value currently held by a variable.
+ Operator and Number ConversionTo convert a number to a string you can either use tostring() function or concatenate the number with empty string.
^ represents 'exponentiation' operator. Also note that there are no ++ or -- operators.
Lua allows multiple assignment of values to the variables.
if...elsewhilerepeat...untilrepeat...until executes the body of the block until the condition becomes true. Also the condition is checked after the body of the block is executed, hence the block is executed at least once.
forThe numeric for has following syntax:
Here i will be 0 at the start. It will be incremented by 2 (this is called as step) for every loop iteration till it becomes 10.
Please note that the variable i is local to the for block.
If you omit the step, it defaults to 1.
Example:
Another example:
If you run this example you will see that this loop executes 11 times to give output:
This shows that all the three expressions are evaluated at the start of the loop. So at the start of the loop k - 100 = 0 hence the loop executes till i becomes 0.
breakIn Lua break can appear only before end or else or until.
Table is a multipurpose data structure in Lua. It can be used as an array or a hash.
As per Lua convention arrays start at index 1. However this is not mandatory. You can even have negative indexes if you want. However Lua libraries expect arrays to start at index 1.
Another way to create an array is:
This will output:
You can access the values using either [] or . notation.
for LoopGeneric for loop can be used to traverse tables as keys and values.
To get both keys and values:
Example:
Please note the use of keyword local. Unless specified local the variables defined in functions are treated as global variables. If we write the above program without the local declaration:
Lua functions can return multiple return values. It's logical as Lua supports multiple assignment.
Example:
Another Example:
My name is Pritam. I am cofounder of Mobisoft Infotech. I live in Pune, India.
This work is available under the Creative Commons Attribution-ShareAlike License