Lua - Quick Guide

Lua - Overview

Lua is extensible light weight programming language written in C. It started as an in-house project in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes.

It was designed from the beginning to be a software that can integrated with code written in C and other conventional languages. This integration brings many benefits. It does not try to do what C can already do but aims at offering what C is not good for: a good distance from the hardware, dynamic structures, no redundancies, ease of testing and debugging. For this, Lua has a safe environment, automatic memory management, and good facilities for handling strings and other kinds of data with dynamic size.

Features

Lua provides a set of unique features that makes it distinct from other languages. These include:

Extensible

Simple

Efficient

Portable

Free and open

Example Code

print("Hello World!")

How Lua is implemented

Lua consists of to parts the Lua interpreter part and the functioning software system. The functioning software system which is an actual computer application that can interpret programs written in the Lua programming language. The Lua interpreter is written in ANSI C, hence it is highly portable and can run on a vast spectrum of devices from highend network servers to small devices.

Both Lua's language and its interpreter are mature, small, and fast.It has evolved from the other programming languages and top software standards. Being small in size makes it possible for it to run on small devices with low memory.

Learning Lua

The most important thing to do when learning Lua is to focus on concepts and not get lost in language technical details.

The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones.

Some Uses of Lua

Game Programming

Scripting in Standalone Applications

Scripting in Web

Extensions and addons for databases like MySQL Proxy and MySQL WorkBench

Security systems like Intrusion Detection System

Lua - Environment

Try it Option Online

You really do not need to set up your own environment to start learning Lua programming language. Reason is very simple, we already have set up Lua Programming environment online, so that you can build and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.

Try following example using Try it option available at the top right corner of the below sample code box:

#!/usr/local/bin/lua
print("Hello World!")

For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning.

Local Environment Setup

If you are still willing to set up your environment for Lua programming language, you need the following two softwares available on your computer, (a) Text Editor, (b) The Lua Interpreter, and (c) Lua Compiler.

Text Editor

This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.

Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.

The files you create with your editor are called source files and contain program source code. The source files for Lua programs are typically named with the extension ".lua".

Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, build it and finally execute it.

The Lua Interpreter

It is just a small program that enables you to type Lua commands and have them executed immediately. It stops execution of a lua file in case it encounters a error unlike a compiler that executes fully.

The Lua Compiler

When we extend Lua to other languages/ applications, we need a Software Development Kit and with a compiler that is compatible with Lua Application Program Interface.

Installation on Mac OS X

In certain cases, you may not have installed Xcode and command line tools. In such cases, you wont be able to use the make command. Install Xcode from mac app store. Then go to Preferences of Xcode and then switch to Downloads and install the component named "Command Line Tools". Once the process is completed, make command will be available to you.

It is not mandatory for you to execute the "make macosx test" statement. Even without executing this command, you can still use Lua in Mac OS X.

We have a helloWorld.lua Lua as follows

print("Hello World!")

Now we can build and run a Lua file say helloWorld.lua by switching to folder containing the file using cd and then using the following command.

$ lua helloWorld

We can see the following output.

hello world

Lua IDE

As mentioned earlier, for Windows SciTE Lua IDE is default IDE provided by the Lua creator team. The alternate IDE available is from ZeroBrane Studio which is available across multiple platforms which include Windows, Mac and Linux.

There are also plugins for eclipse that enable Lua development. Using IDE makes it easier for development with features like code completion and is highly recommended. The IDE also provides interactive mode programming similar to the command line version of Lua.

Lua - Basic Syntax

First Lua Program

Interactive Mode Programming:

Lua provides a mode called interactive mode. In this mode you can type in instructions one after the other and get instant results. This can be invoked in the shell by using the lua -i or just lua command. Once you type in this, press Enter and interactive mode will be started as shown below.

Let's try another way to execute a Lua program. Below is the modified test.lua file:

#!/usr/local/bin/lua
print("test")

Here, I assumed that you have Lua interpreter available in /usr/local/bin directory. The first line is ignored by the interpreter if it starts with # sign. Now, try to run this program as follows:

$ chmod a+rx test.lua
$./test.lua

We will get the following output.

test

Let us now see the basic structure of Lua program, so that it will be easy for you to understand basic building blocks of the Lua programming language.

Tokens in Lua

A Lua program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Lua statement consists of three tokens:

io.write("Hello world, from ",_VERSION,"!\n")

The individual tokens are:

io.write
(
"Hello world, from ",_VERSION,"!\n"
)

Comments

Comments are like helping text in your Lua program and they are ignored by the interpreter. They start with --[[ and terminates with the characters --]] as shown below:

--[[ my first program in Lua --]]

Identifiers

A Lua identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).

Lua does not allow punctuation characters such as @, $, and % within identifiers. Lua is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in Lua. Here are some examples of acceptable identifiers:

mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal

Keywords

The following list shows few of the reserved words in Lua. These reserved words may not be used as constant or variable or any other identifier names.

and

break

do

else

elseif

end

false

for

function

if

in

local

nil

not

or

repeat

return

then

true

until

while

Whitespace in Lua

A line containing only whitespace, possibly with a comment, is known as a blank line, and a Lua interpreter totally ignores it.

Whitespace is the term used in Lua to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement:

local age

There must be at least one whitespace character (usually a space) between local and age for the interpreter to be able to distinguish them. On the other hand, in the following statement

fruit = apples + oranges --get the total fruit

No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.

Lua - Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. It can hold different types of values including finctions 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.

Variable Definition in Lua:

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 nor 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:

For definition without an initializer: variables with static storage duration are implicitly initialized with nil.

Variable Declaration in Lua:

As you can see in the above examples, assignments for multiples variables follows a variable_list and value_list format. In the above example local d , f = 5 ,10 we have d and f in variable_list and 5 and 10 in values list.

Value assigning in Lua takes place like first variable in variable_list with first value in value_list and so on. Hence value of d is 5 and value of f is 10.

Example

Try following example, where variables have been declared at the top, but they have been defined and initialized inside the main function:

Lvalues and Rvalues in Lua:

lvalue : An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.

rvalue : An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.

Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement:

g = 20

But following is not a valid statement and would generate build-time error:

10 = 20

In Lua programming language, apart from the above types of assignment, it is possible to have multiple lvalues and rvalues in the same single statement. It is shown below.

g,l = 20,30

In the above statement, 20 is assigned to g and 30 is assigned to l.

Lua - Data Types

Lua is a dynamically typed language, so the variables don't have types, only the values have types. Values can be stored in variables, passed as parameters and returned as results.

In Lua, though we don't have variable data types, but we have types for the values. The list of data types for values are given below.

Value Type

Description

nil

Used to differentiate the value from having some data or no(nil) data.

boolean

Includes true and false as values. Generally used for condition checking.

number

Represents real(double precision floating point) numbers.

string

Represents array of characters.

function

Represents a method that is written in C or Lua.

userdata

Represents arbitary C data.

thread

Represents independent threads of execution and it is used to implement coroutines.

When you build and execute the above program it produces following result on Linux:

string
number
function
function
boolean
nil
string

By default, all the variables will point to nil until they are assigned a value or intitialized. In Lua, zero and empty strings are considered to be true in case of condition checks. Hence you have to be careful when using boolean operations. We will know more using these types in the next chapters.

Lua - Operators

An operator is a symbol that tells the interpreter to perform specific mathematical or logical manipulations. Lua language is rich in built-in operators and provides following type of operators:

Arithmetic Operators

Relational Operators

Logical Operators

Misc Operators

This tutorial will explain the arithmetic, relational, logical, and other miscellaneous operators one by one.

Operators Precedence in Lua

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Lua - Loops

There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:

Lua programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.

Terminates the loop and transfers execution to the statement immediately following the loop or switch.

The Infinite Loop:

A loop becomes infinite loop if a condition never becomes false. The while loop is often used for this purpose. Since we directly give true for the condition, it keeps executing for ever. We can use break statement to break this loop.

while( true )
do
print("This loop will run forever.")
end

Lua - Decision Making

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Following is the general form of a typical decision making structure found in most of the programming languages:

Lua programming language assumes any combination of boolean true and non-nil values as true, and if it is either boolean false or nil, then it is assumed as false value. It is to be noted that in Lua zero will be considered as true.

Lua programming language provides following types of decision making statements. Click the following links to check their detail.

You can use one if or else if statement inside another if or else if statement(s).

Lua - Functions

A function is a group of statements that together perform a task. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task.

The Lua language provides numerous built-in methods that your program can call. For example, method print() to print the argument passed as input in console.

A function is known with various names like a method or a sub-routine or a procedure etc.

Defining a Function

The general form of a method definition in Lua programming language is as follows:

A method definition in Lua programming language consists of a method header and a method body. Here are all the parts of a method

Optional Function Scope: You can use keyword local to limit the scope the function or ignore the scope section which will make it a global function.

Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.

Arguments: A argument is like a placeholder. When a function is invoked, you pass a value to the argument. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the arguments of a method. Arguments are optional; that is, a method may contain no argument.

Function Body: The method body contains a collection of statements that define what the method does.

Return:In Lua, it is possible to return multiple values by follwing the return keyword with the comma separated return values.

Example:

Following is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two:

--[[ function returning the max between two numbers --]]
function max(num1, num2)
if (num1 > num2) then
result = num1;
else
result = num2;
end
return result;
end

Function Arguments:

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

Calling a Function:

While creating a Lua function, you give a definition of what the function has to do. To use a method, you will have to call that function to perform the defined task.

When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function's end is reached, it returns program control back to the main program.

To call a method you simply need to pass the required parameters along with method name and if method returns a value then you can store returned value. For example:

function max(num1, num2)
if (num1 > num2) then
result = num1;
else
result = num2;
end
return result;
end
-- calling a function
print("The maximum of the two numbers is ",max(10,4))
print("The maximum of the two numbers is ",max(5,6))

When we run the above code, we will get the following output.

The maximum of the two numbers is 10
The maximum of the two numbers is 6

Assigning and passing functions

In Lua, we can assign the function to variables and also can pass them as parameters of another function. Here is a simple example for assigning passing a function as parameter in lua.

Function with variable argument

It is possible to create functions with variable arguments in Lua uing ... as its parameter. We can get a grasp of this by seeing an example in which the function will return the average and it can take variable arguments.

function average(...)
result = 0
local arg={...}
for i,v in ipairs(arg) do
result = result + v
end
return result/#arg
end
print("The average is",average(10,5,3,4,5,6))

When we run the above code, we will get the following output.

The average is 5.5

Lua - Strings

String is a sequence of characters as well as control characters like form feed. String can be initialized with three forms which includes,

Escape sequence characters are used in string to change the normal interpretation of character. For example to print double inverted commas(""), we have used \" in the above example. The escape sequence and its use is listed below in the table.

Escape Sequence

Use

\a

Bell

\b

Backspace

\f

Formfeed

\n

New line

\r

Carriage return

\t

Tab

\v

Vertical tab

\\

Backslash

\"

Double quoutes

\'

Single quotes

\[

Left square bracket

\]

Right square bracket

String manipulation

Lua supports string manipulate strings:

S.N.

Method & Purpose

1

string.upper(argument):

Returns a capitalized representation of the argument.

2

string.lower(argument):

Returns a lower case representation of the argument.

3

string.gsub(mainString,findString,replaceString)

Returns a string by replacing occurrences of findString with replaceString.

Character and byte representations

A sample code for character and byte representation which is used for converting the string from string to internal representation and vice versa.

-- Byte conversion
-- First character
print(string.byte("Lua"))
-- Third character
print(string.byte("Lua",3))
-- first character from last
print(string.byte("Lua",-1))
-- Second character
print(string.byte("Lua",2))
-- Second character from last
print(string.byte("Lua",-2))
-- Internal Numeric ASCII Conversion
print(string.char(97))

When we run the above program, we will get the following output.

76
97
97
117
117
a

Other common functions

The common string manipulations include string concatenation, finding length of string and at times repeating the same string multiple times. The example for these operations is given below.

Lua - Arrays

Arrays are ordered arrangement of objects which may be a single dimensional array containing a collection of rows or multi-dimensional array containing multiple rows and columns.

In Lua, arrays are implemented using indexing tables with integers. The size of arrays is not fixed and it can grow based on our need subject to memory constraints.

Single Dimensional Array

A single dimensional array can be represented using a simple table structure and can be initialized and read using a simple for loop. An example is shown below.

array = {"Lua", "Tutorial"}
for i= 0, 2 do
print(array[i])
end

When we run the above code, we wil get the following output.

nil
Lua
Tutorial

As you can see in the above code, when we are trying to access an element in an index that is not there in the array, it returns nil. In Lua indexing generally starts at index 1. But it is possible to create objects at index 0 and below 0 as well. Array using negative indices is shown below where we initialize the array using a for loop.

array = {}
for i= -2, 2 do
array[i] = i *2
end
for i = -2,2 do
print(array[i])
end

When we run the above code, we wil get the following output.

-4
-2
0
2
4

Multi-Dimensional Array

Multi-Dimensional arrays can be implemented in two way.

Array of arrays

Single dimensional array by manipulating indices

An example for multidimensional array of 3,3 is shown below using array of arrays.

-- Initializing the array
array = {}
for i=1,3 do
array[i] = {}
for j=1,3 do
array[i][j] = i*j
end
end
-- Accessing the array
for i=1,3 do
for j=1,3 do
print(array[i][j])
end
end

When we run the above code, we wil get the following output.

1
2
3
2
4
6
3
6
9

An example for multidimensional array of 3,3 is shown below using manipulating indices.

-- Initializing the array
array = {}
maxRows = 3
maxColumns = 3
for row=1,maxRows do
for col=1,maxColumns do
array[row*maxColumns +col] = row*col
end
end
-- Accessing the array
for row=1,maxRows do
for col=1,maxColumns do
print(array[row*maxColumns +col])
end
end

When we run the above code, we wil get the following output.

1
2
3
2
4
6
3
6
9

As you can see in the above example, data is stored based on indices. It is possible to place the elements in a sparse way and it is the way lua implemention of a matrix works. Since it does not store nil values in lua, it is possible to save lots of memory without any special technique in lua as compared to special techniques used in other programming languages.

Lua - Iterators

Iterator is a construct that enables you to traverse through the elements of the so called collection or container. In Lua, these collections often refer to tables which are used to create various data structures like array.

Generic For Iterator

A generic for iterator provides the key value pairs of each element in the collection. A simple example is given below.

array = {"Lua", "Tutorial"}
for key,value in ipairs(array)
do
print(key, value)
end

In Lua we use functions to represent iterators. Based on the state maintenance in these iterator functions, we have two main types:

Stateless Iterators

Stateful Iterators

Stateless Iterators

By the name itself we can understand that this type of iterator function don't retain any state.

Let us now see an example of creating our own iterator using a simple function that prints the squares of n numbers.

function square(iteratorMaxCount,currentNumber)
if currentNumber<iteratorMaxCount
then
currentNumber = currentNumber+1
return currentNumber, currentNumber*currentNumber
end
end
for i,n in square,3,0
do
print(i,n)
end

When we run the above program, we will get the following output.

1 1
2 4
3 9

The above code can be modified slightly to mimic the way ipairs function of iterators work. It is shown below.

function square(iteratorMaxCount,currentNumber)
if currentNumber<iteratorMaxCount
then
currentNumber = currentNumber+1
return currentNumber, currentNumber*currentNumber
end
end
function squares(iteratorMaxCount)
return square,iteratorMaxCount,0
end
for i,n in squares(3)
do
print(i,n)
end

When we run the above program, we will get the following output.

1 1
2 4
3 9

Stateful Iterators

The previous example of iteration using function does not retain the state. Each time the function is called, it returns the next element of the collection based on a second variable sent to the function. To hold the state of the current element, closures are used. Closure retain variables values across functions calls. To create a new closure, we create two functions including the closure itself and a factory, the function that creates the closure.

Let us now see an example of creating our own iterator in which we will be using closures.

array = {"Lua", "Tutorial"}
function elementIterator (collection)
local index = 0
local count = #collection
-- The closure function is returned
return function ()
index = index + 1
if index <= count
then
-- return the current element of the iterator
return collection[index]
end
end
end
for element in elementIterator(array)
do
print(element)
end

When we run the above program, we will get the following output.

Lua
Tutorial

In the above example, we can see that elementIterator has another method inside that uses the local external variables index and count to return each of the element in the collection by incrementing the index each time the function is called.

We can create our own function iterators using closure as shown above and it can return muliple elements for each of the time we iterate through the collection

Lua - Tables

Introduction

Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need.

Lua uses tables in all representations including representation of packages. When we access a method string.format, it means, we are accessing the format function available in string package.

Representation and Usage

Tables are called objects and they are neither values nor variables. Lua uses a constructor expression {} to create an empty table. It is to be know that there is no fixed relationship between a variable that holds reference of table and the table itself.

When we have a table a with set of elements and if we assign it to b, both a and b refer to the same memory. No separate memory is allocated separately for b. When a is set to nil, table will be still accessible to b. When there are no reference to a table, then garbage collection in Lua takes care of cleaning up process to make these unreferenced memory to be reused again.

An example is shown below for explaining the above mentioned features of tables.

Type of mytable is table
mytable Element at index 1 is Lua
mytable Element at index wow is Tutorial
alternatetable Element at index 1 is Lua
mytable Element at index wow is Tutorial
mytable Element at index wow is I changed it
alternatetable is nil
mytable Element at index wow is I changed it
mytable is nil

Table manipulation

There are in built functions for table manipulation and they are listed in the following table.

S.N.

Method & Purpose

1

table.concat (table [, sep [, i [, j]]]):

Concatenates the strings in the tables based on the parameters given. See example for detail.

2

table.insert (table, [pos,] value):

Inserts a value into the table at specified position.

3

table.maxn (table)

Returns the largest numeric index.

4

table.remove (table [, pos])

Removes the value from the table.

5

table.sort (table [, comp])

Sorts the table based on optional comparator argument.

Let see some samples of above functions.

Table Concatenation

We can use the concat function to concatenate two tables as shown below.

Lua - Modules

What is a Module?

Module is a like a library that can be loaded using require and has a single global name containing a table. This module can consist of a number of functions and variables. All these functions and variables are wrapped in to the table which acts as a namespace. Also a well behaved module has necessary provisions to return this table on require.

Speciality of Lua modules

The usage of tables in modules helps us in numerous ways and enable us to manipulate the modules in the same way we manipulate any other lua table. As a result of the ability to manipulate modules, it provides extra features for which other languages need special mechanisms. Due to this free mechanism of modules in lua, an user can call the functions in lua in multiple ways. A few of them are shown below.

In the above sample code, you can see how flexible programming in Lua is without any special additional code.

The require Function

Lua has provided a high level function called require to load all the necessary modules. It is kept as simple as possible to avoid having too much information on module to load it. The require function just assumes the modules as a chunk of code that defines some values which is actually functions or tables containing functions.

Example

Let us consider a simple example where one function has the math functions and lets call this module as mymath and filename being mymath.lua. The file content is as follows.

In order to run this code, we need to place the two lua files in the same directory or alternatively, you can place the module file in the package path and it needs additonal setup. When we run the above program, we will get the following output.

30
10
200
1.5

Things to remember

Place both the module and the file you run in the same directory.

Module name and its file name should be the same.

It is a best practice to return modules for require function and hence the module should be preferably implemented as shown above eventhough you can find other types of implementations else where.

Old way of implementing modules

Let me now rewrite the same example in the older way which uses package.seeall type of implementation. This was used in Lua versions 5.1 and 5.0. The mymath module is shown below.

When we run the above, we will get the same output. But it is advised on to use the older version of the code and it is assumed to less secure. Many SDKs that use Lua for programming like Corona SDK has deprecated the use of this.

Lua - Metatables

A metatable is a table that helps in modifying the behavior of a table it is attached to with the help of a key set and related meta methods. These meta methods are powerful lua functionality that enables features like,

Changing/adding functionalities to operators on tables

Looking up metatables when the key is not available in the table using __index in metatable.

There are two important methods that are used in handling metatables which includes,

setmetatable(table,metatable): This method is used to set metatable for a table.

getmetatable(table): This method is used to get metatable of a table.

Lets first look at how to set one table as metatable of another. It is shown below.

mytable = {}
mymetatable = {}
setmetatable(mytable,mymetatable)

The above code can be represented in a single line as shown below.

mytable = setmetatable({},{})

__index

A simple example of metatable for looking up the meta table when it's not available in table is shown below.

__newindex

When we add __newindex to metatable, if keys are not available in the table, the behaviour of new keys will be defined by meta methods. A simple example where metatable's index is set when index is not available in main table is given below.

If you know the capabilities of meta table fully, you can really perform a lot of operations that would be very complex without using it. So try to work more on using metatables with different options available in meta tables as explained in the samples and also create your own samples.

Lua - Coroutines

Introduction

Coroutines are collaborative in nature which allows two or more methods to execute in a controlled manner. With coroutines, at any given time, there is only one of its coroutines runs and this running coroutine only suspends its execution when it explicitly requests to be suspended.

The above definition may look vague. So let me tell it more clearly, assume we have two methods, one the main program method and a coroutine. When we call a coroutine using resume function, its starts executing and when we call yield function, it suspend executing. Again the same coroutine can continue executing with another resume function call from where it was suspended. This process can continue till the end of execution of the coroutine.

Functions available in coroutines

The following table lists all the available functions for corountines in lua and their corresponding use.

S.N.

Method & Purpose

1.

coroutine.create (f):

Creates a new coroutine with a function f and returns an object of type "thread".

2.

coroutine.resume (co [, val1, ...]):

Resumes the corountine co and passes the parameters if any. It returns status of operation and optional other return values.

3.

coroutine.running ():

Returns the running coroutine or nil if called in the main thread.

4.

coroutine.status (co):

Returns one of the values from running, normal, suspended or dead based on the state of the coroutine.

5.

coroutine.wrap (f):

Like coroutine.create, the coroutine.wrap function also creates a coroutine, but instead of returning the coroutine itself, it returns a function that, when called, resumes the coroutine.

6.

coroutine.yield (...):

Suspends the running coroutine. The parameter passed to this method acts as additional return values to the resume function.

What does the above example do?

As mentioned before, we use the resume function to start the operation and yield function to stop the operation. Also, you can see how that there are multiple return values received by resume function of coroutine. I will explain each of the steps in the above program to make it clear.

First, we create a coroutine and assign it to variable name co and the coroutine takes in two variables as its parameters.

When we call the first resume function, the values 3 and 2 are retained in the temporary variables value1 and value2 till the end of the coroutine.

To make you understand this, we have used a tempvar3 which is 10 initially and it gets updated to 13 and 16 by the subsequent calls of the coroutines since value1 is retained as 3 throughout the execution of the coroutine.

The first coroutine.yield returns two values 4 and 3 to the resume function which is got by updating the input params 3 and 2 in the yield statement. It also receives the true/false status of coroutine execution.

Another thing about coroutines is how the next params of resume call as taken care of, in the above example; you can see that the variable the coroutine.yield assigns recieves the next call params which provides a powerful way of doing new operation with the retentionship of existing param values.

Finally, once all the statements in the coroutines are executed, the subsequent calls will return in false and "cannot resume dead coroutine" statement as response.

Another coroutine example

Let us look at a simple coroutine that returns a number from 1 to 5 with the help of yield function and resume function. It creates coroutine if not available or else resumes the existing coroutine.

There is often a comparison of coroutines with the threads of multiprogramming languages, but we need to understand that coroutines have similar features of thread but execute only one at a time and never executes concurrently.

We control the program execution sequence to meet of needs with the provision of retaining certain information temporarily. Using global variables with coroutines, provides even more flexibility for coroutines.

Lua - File I/O

I/O library is used for reading and manipulating files in Lua. There are two kinds of file operations in Lua namely implicit file descriptors and explicit file descriptors.

For the following examples, we will use a sample file test.lua as shown below.

-- sample test.lua
-- sample2 test.lua

A simple file open operation uses the following statement.

file = io.open (filename [, mode])

The various file modes are listed in the following table.

Mode

Description

"r"

Read-only mode and is the default mode where an existing file is opened.

"w"

Write enabled mode that overwites existing file or creates a new file.

"a"

Append mode that opens an existing file or a creates a new file for appending.

"r+"

Read and write mode for an existing file.

"w+"

All existing data is removed if file exists or new file is created with read write permissions.

"a+"

Append mode with read mode enabled that opens an existing file or creates a new file.

Implicit file descriptors

Implicit file descriptors use the standard input/ output modes or using a single input and single output file. A sample of using implicit file descriptors is shown below.

-- Opens a file in read
file = io.open("test.lua", "r")
-- sets the default input file as test.lua
io.input(file)
-- prints the first line of the file
print(io.read())
-- closes the open file
io.close(file)
-- Opens a file in append mode
file = io.open("test.lua", "a")
-- sets the default output file as test.lua
io.output(file)
-- appends a word test to the last line of the file
io.write("-- End of the test.lua file")
-- closes the open file
io.close(file)

When you run the program, you will get an output of the first line of test.lua file. For me, I got the following output.

-- Sample test.lua

This was the first line of the statement in test.lua file for me. Also the line "-- End of the test.lua file" would be appended to the last line of test.lua code

In the above example you can see how the implicit descriptors work with file system using the io."x" methods. The above example uses io.read() without the optional parameter. The optional parameter can be any of the following.

Mode

Description

"*n"

Reads from the current file position and returns a number if exists at the file position or returns nil.

"*a"

Returns all the contents of file from the current file position.

"*l"

Reads the line from the current file position, and moves file position to next line.

number

Reads number of bytes specified in the function.

Other common io methods includes,

io.tmpfile(): Returns a temporary file for reading and writing that will be removed once the program quits.

io.type(file): Returns whether file, closed file or nil based on the input file.

io.flush(): Clears the default output buffer.

io.lines(optional file name): Provides an generic for loop iterator that loops through the file and closes the file in the end in case file name is provided or the default file is used and not closed in the end of the loop.

Explicit file descriptors

We often use explicit file descriptor which allows us to manipulate multiple files at a time. These functions are quite similar to implicit file descriptors. Here, we use file:function_name instead of io.function_name. The following example of the file version of the same implicit file descriptors example is shown below.

-- Opens a file in read mode
file = io.open("test.lua", "r")
-- prints the first line of the file
print(file:read())
-- closes the opened file
file:close()
-- Opens a file in append mode
file = io.open("test.lua", "a")
-- appends a word test to the last line of the file
file:write("--test")
-- closes the open file
file:close()

When you run the program, you will get an similar output as the implicit descriptors example.

-- Sample test.lua

All the modes of file open and params for read for external descriptors is same as implicit file descriptors.

Other common file methods includes,

file:seek(optional whence, optional offset): Whence parameter is "set", "cur" or "end". Sets the new file pointer with the updated file position from the beginning of the file. The offsets are zero-based in this function. The offset is measured from the beginning of the file if the first argument is "set"; from the current position in the file if it's "cur"; or from the end of the file if it's "end". The default argument values are "cur" and 0, so the current file position can be obtained by calling this function without arguments.

file:flush(): Clears the default output buffer.

io.lines(optional file name): Provides an generic for loop iterator that loops through the file and closes the file in the end in case file name is provided or the default file is used and not closed in the end of the loop.

An example to use the seek method is shown below. It offsets the cursor from the 25 positions prior to the end of file. The read function prints remainder of the file from seek position.

You can play around all the different modes and parameters to know the full ability of the Lua file operations.

Lua - Error Handling

Need for Error handling

Error handling is necessary due to real world operations often require the use of complex operations which includes file operations, database transaction and web service calls. The errors uncared can lead to big losses when doing a business that involves confidential information or money transactions.

In any programming, there is always a requirement for error handling. Errors can be of two types which includes,

Syntax errors

Run time errors

Syntax errors

Syntax errors occur due to improper use of various program components like operators and expressions. A simple example for syntax error is shown below.

a == 2

As you know, there is difference between use of a single equal to and double equal to. Using one instead of the other can lead to error. One equal to, refers to assignment while double equal to refers to comparison. Similarly, we have expressions and functions that have its predefined way of implementing them.

Another example for syntax error is shown below.

for a= 1,10
print(a)
end

When we run the above program, we will get the following output.

lua: test2.lua:2: 'do' expected near 'print'

Syntax errors are much easier to handler than run time errors since, the lua interpreter locates the error more clearly than in case of runtime error. From the above error, we can know easily that adding a do statement before print statement is required as per the Lua structure.

Run time errors

In case of runtime errors, the program executes successfully, but it can result in run time errors due mistakes in input or mishandled functions. A simple example to show run time error is shown below.

function add(a,b)
return a+b
end
add(10)

When we build the program, it will build successfully and run. Once it runs, it will run and shows an run time error.

This is a run time error which had occurred due to not passing two variables. The b parameter is expected and here it is nil and produces an error.

Assert and Error functions

In order to handle error, we often use two functions assert and error. A simple example is shown below.

local function add(a,b)
assert(type(a) == "number", "a is not a number")
assert(type(b) == "number", "b is not a number")
return a+b
end
add(10)

When we run the above program, we will get the following error output.

lua: test2.lua:3: b is not a number
stack traceback:
[C]: in function 'assert'
test2.lua:3: in function 'add'
test2.lua:6: in main chunk
[C]: ?

The error (message [, level]) terminates the last protected function called and returns message as the error message. This function error never returns. Usually, error adds some information about the error position at the beginning of the message. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.

pcall and xpcall

In Lua programming, in order to avoid throwing these errors and handling errors, we need to use the functions pcall or xpcall.

The pcall (f, arg1, ...) function calls the requested function in protected mode. If some error occurs in function f, it does not throw an error. It just returns the status of error. A simple example using pcall is shown below.

The xpcall (f, err) function calls the requested function and also sets the error handler. Any error inside f is not propagated; instead, xpcall catches the error, calls the err function with the original error object, and returns a status code.

As a programmer it is most important to ensure that you take care of proper error handling in the programs you write. Using error handling can ensure that unexpected conditions beyond the boundary conditions are handled without disturbing the user of the program.

Lua - Debugging

Lua provides a debug library which provides all the primitive functions for us to create our own debugger. Even though, there is no in-built Lua debugger, we have many debuggers for Lua created by various developers with many being open source.

The functions available in the Lua debug library are listed in the following table along with its uses.

S.N.

Method & Purpose

1.

debug():

Enters interactive mode for debugging which remains active till we type in only cont in a line and press enter. User can inspect variables during this mode using other functions.

2.

getfenv(object):

Returns the environment of object.

3.

gethook(optional thread):

Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count.

4.

getinfo(optional thread, function or stack level, optional flag):

Returns a table with info about a function. You can give the function directly, or you can give a number as the value of function, which means the function running at level function of the call stack of the given thread: level 0 is the current function (getinfo itself); level 1 is the function that called getinfo; and so on. If function is a number larger than the number of active functions, then getinfo returns nil.

5.

getlocal(optional thread, stack level, local index):

Returns the name and the value of the local variable with index local of the function at level level of the stack.Returns nil if there is no local variable with the given index, and raises an error when called with a level out of range.

6.

getmetatable(value):

Returns the metatable of the given object or nil if it does not have a metatable.

7.

getregistry():

Returns the registry table,a pre-defined table that can be used by any C code to store whatever Lua value it needs to store.

8.

getupvalue(function, upvalue index):

This function returns the name and the value of the upvalue with index up of the function func. The function returns nil if there is no upvalue with the given index.

9.

setfenv(function or thread or userdata, environment table):

Sets the environment of the given object to the given table. Returns object.

Sets the given function as a hook. The string mask and the number count describe when the hook will be called. Here, c, r and l are called every time lua calls, returns and enters every line of code in a function respectively.

11.

setlocal(optional thread, stack level, local index, value):

Assigns the value value to the local variable with index local of the function at level level of the stack. The function returns nil if there is no local variable with the given index, and raises an error when called with a level out of range. Otherwise, it returns the name of the local variable.

12.

setmetatable(value, metatable):

Sets the metatable for the given object to the given table (which can be nil).

13.

setupvalue(function, upvalue index, value):

This function assigns the value value to the upvalue with index up of the function func. The function returns nil if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.

The above list is the complete list of debug functions in Lua and we often use a library that uses the above functions and provides easier debugging. Using these functions and creating our own debugger is quite complicated and is not preferable. Anyway, we will see an example of simple use of debugging functions.

In the above sample program, the stack trace is printed by using the debug.trace function available in the debug library. The debug.getinfo gets the current table of the function.

Another Example

We often may need to know the local variables of a function for debugging. For that purpose, we can use getupvalue and to set these local variables, we use setupvalue. A simple example for this is shown below.

In this example, the counter updates by one each time it is called. We can see the current state of the local variable using the getupvalue function. We then set the local variable to a new value. Here, n is 2 before the set operation is called. Using setupvalue function, it is updated to 10. Now when we call the counter function, it will return 11 instead of 3.

Debugging Types

Command line debugging

Graphical debugging

Command line debugging

Command line debugging is the type of debugging that uses command line to debug with the help of commands and print statements. There are many command line debuggers available for Lua of which a few are listed below.

RemDebug: RemDebug is a remote debugger for Lua 5.0 and 5.1. It lets you control the execution of another Lua program remotely, setting breakpoints and inspecting the current state of the program. RemDebug can also debug CGILua scripts.

clidebugger: A simple command line interface debugger for Lua 5.1 written in pure Lua. It's not dependent on anything other than the standard Lua 5.1 libraries. It was inspired by RemDebug but does not have its remote facilities.

ctrace: A tool for tracing Lua API calls.

xdbLua: A simple Lua command line debugger for the Windows platform.

LuaInterface - Debugger: This project is a debugger extension for LuaInterface. It raises the built in Lua debug interface to a higher level. Interaction with the debugger is done by events and method calls.

Rldb: This is a remote lua debugger via socket, available on both Windows and Linux. It can give you much more features than any existing one.

ModDebug: This allows to controllling the execution of another Lua program remotely, set breakpoints, and inspect the current state of the program.

Graphical debugging

Graphical debugging is available with the help of IDE where you are provided with visual debugging of various states like variable values, stack trace and other related information. There is a visual representation and step by step control of execution with the help of breakpoints, step into, step over and other buttons in the IDE.

There are number of graphical debuggers for Lua and it includes the following.

Lua - Garbage Collection

Lua uses automatic memory management that uses garbage collection based on certain algorithms that is in-built in Lua. As a result of automatic memory management, as a developer,

No need to worry about allocating memory for objects.

No need to free them when no longer needed except for setting it to nil.

Lua uses a garbage collector that runs from time to time to collect dead objects when they are no longer accessible from the Lua program.

All objects including tables, userdata, functions, thread, string and so on are subject to automatic memory management. Lua uses incremental mark and sweep collector that uses two numbers to control its garbage collection cycles namely garbage collector pause and garbage collector step multiplier. These values are in percentage and value of 100 is often equal to 1 internally.

Garbage collector pause

Garbage collector pause is used for controlling how long the garbage collector needs to wait, before; it is called again by the Lua's automatic memory management. Values less than 100 would mean that the Lua will not wait for the next cycle. Similary higher values of this value would result in the garbage collector being slow and less aggressive in nature. A value of 200, means that the collector waits for the total memory in use to double before starting a new cycle. Hence, depending on the nature and speed of application, there may a requirement to alter this value to get best performance in Lua applications.

Garbage collector step multiplier

This step multiplier controls the relative speed of garbage collector to that of memory allocation in Lua program. Larger step values will lead to garbage collector to be more aggresive and it also increases the step size of each incremental step of garbage collection. Values less than 100 could often lead to avoid the garbage collector not to complete its cycle and its not generally preferred. The default value is 200, which means the garbage collector runs twice as the speed of memory allocation.

Garbage collector functions

As developers, we do have some control over the automatic memory management in Lua. For this we have the following methods.

collectgarbage("collect"): Run one complete cycle of garbage collection.

collectgarbage("count"): Returns the amount of memory currently used by the program in Kilobytes

collectgarbage("restart"): If the garbage collector has been stopped, it restarts it.

collectgarbage("setpause"): Set the value given as second parameter divided by 100 to the garbage collector pause variable. Its uses are as discussed a little above.

collectgarbage("setstepmul"): Set the value given as second parameter divided by 100 to the garbage step multiplier variable. Its uses are as discussed a little above.

collectgarbage("step"): Runs one step of garbage collection. The larger the second argument is, the larger this step will be. The collectgarbage will return true if the triggered step was the last step of a garbage-collection cycle.

When we run the above program, we will get the following output. Please note that this result will vary due to difference in type of operating system and also the automatic memory management feature of Lua.

20.9560546875
20.9853515625
0
19.4111328125

You can see in the above program, once garbage collection is done, it reduced the memory used. But, it's not mandatory to call this. Even if we don't call them, it will executed automatically at a later stage by Lua interpreter after the predefined period.

Obviously, we can change the behaviour of the garbage collector using these functions if required. These functions provide a bit of additional capability for the developer to handle complex situations. Depending on the type of memory need for the program you do, you may or may not use this feature. But it is very useful to know the memory usage in the applications and check it during programming itself to avoid undesired results after deployment.

Lua - Object Oriented

Introduction to OOP

Object Oriented Programming(OOP), is one the most used programming technique that us used in the modern era of programming. There are a number of programming languages that support OOP which include,

C++

Java

Objective-C

Smalltalk

C#

Ruby

Features of OOP

Class: A class is an extensible template for creating objects, providing initial values for state (member variables) and implementations of behavior.

Objects: It is an instance of class and has separate memory allocated for itself.

Inheritance: It is a concept by which variables and functions of one class is inherited by another class.

Encapsulation: It is the process of combining the data and functions inside a class. Data can be accessed outside the class with the help of functions. It is also known as data abstraction.

OOP in Lua

You can implement object orientation in Lua with the help of tables and first class functions of Lua. By placing functions and related data into a table, an object is formed. Inheritance can be implemented with the help of metatables, providing a look up mechanism for nonexistent functions(methods) and fields in parent object(s).

Tables in Lua have the features of object like state and identity that is independent of its values. Two objects (tables) with the same value are different objects, whereas an object can have different values at different times, but it is always the same object. Like objects, tables have a life cycle that is independent of who created them or where they were created.

A real world example

The concept of object orientation is widely used but you need to understand it clearly for proper and maximum benefit.

Let us consider a simple math example. We often encounter situations where we work on different shapes like circle, rectangle and square.

The shapes can have a common property Area. So, we can extend other shapes from the base object shape with the common property area. Each of the shapes can have its own properties and functions like a rectangle can have properties length, breadth, area as its properties and printArea and calculateArea as its functions.

Creating a simple class

A simple class implementation for rectangle three properties area, length and breadth is shown below. It also has a printArea function to print the area calculated.

Creating Object

Creating object is the process of allocating memory for the class instance. Each of the objects has its own memory and share the common class data.

r = Rectangle:new(nil,10,20)

Accessing properties

We can access the properties in the class using the dot operator as shown below

print(r.length)

Accessing member function

You can access member function using the colon operator with the object as shown below.

r:printArea()

The memory gets allocated and the initial values are set. The initialization process can be compared to constructors in other object oriented languages. It is nothing but a function that enables setting values as shown above.

Inheritance complete example

We can extend the simple class implementation in Lua as shown above with help another new method with the help of metatables. All the member variables and functions of base class are retained in the derived class.

The area is 100
The area of square is 100
The area of Rectangle is 200

In the above example, we have created two derived classes Rectangle and Square from the base class Square. It is possible to overide the functions of base class in derived class. In this example, the derived class overides the function printArea.

Lua - Web Programming

Lua is highly flexible language and it is often used in multiple platforms including web applications. The Kepler community that was formed 2004 to provide open source web components in Lua.

Even though, there are other web frameworks using Lua have been developed, we will be primarily focused on components provided by Kepler community.

Applications and Frameworks

Orbit is an MVC web framework for Lua, based on WSAPI.

WSAPI is the API that abstracts the web host server from Lua web applications and is the base for many projects.

Xavante is a Lua Web server that offers a WSAPI interface.

Sputnik is a wiki/CMS developed over WSAPI on Kepler Project used for humor and entertainment.

CGILua offers LuaPages and LuaScripts web page creation, based on WSAPI but no longer supported. Use Orbit, Sputnik or WSAPI instead.

In this tutorial, we will try to make you understand what Lua can do and to know more about it installation and usage, refer kepler website

Orbit

Orbit is an MVC web framework for Lua. It completely abandons the CGILua model of "scripts" in favor of applications, where each Orbit application can fit in a single file, but you can split it into multiple files if you want.

All Orbit applications follow the WSAPI protocol, so they currently work with Xavante, CGI and Fastcgi. It includes a launcher that makes it easy to launch a Xavante instance for development.

The easiest way to install Orbit is using LuaRocks. luarocks install orbit is the command for installing. For this, first you need to install LuaRocks first.

If you haven't installed all the dependencies, here is the steps to be followed to setup Orbit in Unix/Linux enviroment.

Install LuaRocks

Install WSAPI, FCGI, Orbit, and Xavante

Setting up Apache2

$ sudo raj /etc/apache2/sites-available/default

Add this following section below the <Directory /var/www/> section of the config file. If this section has a 'AllowOverride None' then you need to change the 'None' to 'All' so that the .htaccess file can override the configuration locally.

You can see in the above code a simple html page is formed and returned. You can see the usage of coroutines that makes it possible to return statement by statement to calling function. Finally html status code(200), headers and html page is returned.

Xavante

Xavante is a Lua HTTP 1.1 Web server that uses a modular architecture based on URI mapped handlers. Xavante currently offers,

File handler

Redirect handler

WSAPI handler

File handler is used for general files. Redirect handler enabes URI remapping and WSAPI handler for handing with WSAPI applications.

These web frameworks can leverage your web applications and help you in doing powerful operations.

Lua - Database Access

For simple data operations, we may use files but, sometimes these file operations may not be efficient, scalable and powerful. For this purpose, we may often switch to using databases. LuaSQL is a simple interface from Lua to a number of database management systems. LuaSQL is the library which provides support for different types of SQL. This include,

SQLite

Mysql

ODBC

In this tutorial, I will be covering database handling of MySQL an SQLite in Lua. This uses a generic interface for both and should be possible to port this implementation to other types of databases as well. First let see how you can do the operations in MySQL.

MySQL db setup

In order to use the following examples to work as expected, we need the initial db setup. The assumptions are listed below.

You have installed and setup MySQL with default user as root and password as '123456'.

Importing MySQL

We can use a simple require statement to import the sqlite library assuming that your Lua implementation was done correctly. During installation, a folder libsql that contains the database related files.

mysql = require "luasql.mysql"

The variable mysql will provide access to the functions by referring to the main mysql table.

Setting up connection

We can set up the connection by initiating an MySQL environment and then creating a connection for the environment. It is shown below.

When you run the above program, a table named sample will be created with two columns namely, id and name.

MySQL environment (004BB178) MySQL connection (004BE3C8)
0 nil

In case there is any error, you would be returned a error statement instead of nil. A simple error statement is shown below.

LuaSQL: Error executing query. MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"id INTEGER, name TEXT)' at line 1

Insert statement example

An insert statement for MySQL is shown below.

conn:execute([[INSERT INTO sample values('11','Raj')]])

Update statement example

An update statement for MySQL is shown below.

conn:execute([[UPDATE sample3 SET name='John' where id ='12']])

Delete statement example

A delete statement for MySQL is shown below.

conn:execute([[DELETE from sample3 where id ='12']])

Select statement example

As far as select statement is concerned, we need to loop through each of the rows and extract the required data. A simple select statement is shown below.

Performing Transactions:

Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties:

Atomicity: Either a transaction completes or nothing happens at all.

Consistency: A transaction must start in a consistent state and leave the system in a consistent state.

Isolation: Intermediate results of a transaction are not visible outside the current transaction.

Durability: Once a transaction was committed, the effects are persistent, even after a system failure.

Transaction starts with START TRANSACTION; and ends with commit or rollback statement.

Start transaction

Inorder to initiate a transaction, we need to do execute the following statement in Lua assuming conn is an open MySQL connection.

conn:execute([[START TRANSACTION;]])

Rollback transaction

We need to do execute the following statement to rollback changes made after start transaction is executed.

conn:execute([[ROLLBACK;]])

Commit transaction

We need to do execute the following statement to commit changes made after start transaction is executed.

conn:execute([[COMMIT;]])

We have known about MySQL in the above and following section explains about basic SQL operations. Remember transactions, though not explained again for SQLite3 but the same statements should work for SQLite3 as well.

Importing SQLite

We can use a simple require statement to import the sqlite library assuming that your Lua implementation was done correctly. During installation, a folder libsql that contains the database related files.

sqlite3 = require "luasql.sqlite3"

The variable sqlite3 will provide access to the functions by referring to the main sqlite3 table.

Setting up connection

We can set up the connection by initiating an sqlite environment and then creating a connection for the environment. It is shown below.

local env = sqlite3.sqlite3()
local conn = env:connect('mydb.sqlite')

The above connection will connect to an existing sqlite file or creates a new sqlite file and establishes the connection with the newly created file.

Execute function

There is a simple execute function available with the connection that will help us to do all the db operations from create, insert, delete, update and so on. The syntax is shown below

conn:execute([[ 'SQLite3STATEMENT' ]])

In the above syntax we need to ensure that conn is open and existing sqlite3 connection and replace the 'SQLite3STATEMENT' with the correct statement.

Create table example

A simple create table example is shown below. It creates a table with two parameters id of type integer and name of type varchar.

We can execute all the available queries with the help of this libsql library. So please don't stop with these examples. Experiment various query statement available in respective MySQL, SQLite3 and other supported db in Lua.

Lua - Game Programmig

Lua is used in a lot of game engines due to its simple language structure and syntax. Also, the garbage collection feature is often quite usefu for the games which consume lot of memory due to rich graphics that is used. Some game engines using Lua includes,

Corona SDK

Gideros Mobile

ShiVa3D

Moai SDK

LOVE

CryEngine

Each of these game engines are based on Lua and there is rich set of API available in each of these engines. We will look at the capabilities of each in brief.

Corona SDK

Corona SDK is a cross platorm mobile game engine that supports iPhone, iPad, and Android platforms. There is a free version of Corona SDK that can be used for small games with limited features. You can upgrade to other versions when needed.

Corona SDK provides a number of features which includes,

Physics and Collision handling APIs

Web and Network APIs

Game Network API

Ads API

Analytics API

Database and File System APIs

Crypto and Math APIs

Audio and Media APIs

Using the above APIs, makes it easier to develop much faster than using the native APIs separately for iOS and Android.

Gideros Mobile

Gideros provides the cross-platform SDK to create games for iOS and Android. It is free to use with a made with Gideros splash. Some of the striking advantages in Gideoros includess,

Development IDE: It provides its own IDE which makes it easier to develop Gideros apps.

Instant testing: While developing your game, it can be tested on a real device through Wifi in only 1 second. You don't need to waste your time with an export or deploy process.

Plugins: You can easily extend the core with plugins. Import your existing (C, C++, Java or Obj-C) code, bind to Lua and interpret them directly. Dozens of open-source plugins are already developed and ready to use.

Clean OOP approach: Gideros provides its own class system with all the basic OOP standards, enabling you to write clean and reusable code for any of your future games.

Native speed: Developed on top of C/C++ and OpenGL, your game runs at native speed and fully utilizes the power of CPUs and GPUs underneath.

ShiVa3D

ShiVa3D is one of 3D game engines which provides a graphical editor designed to create applications and video games for the Web, Consoles and Mobile devices. It supports mutiple platforms which includes, Windows, Mac, Linux, iOS, Android, BlackBerry, Palm OS, Wii and WebOS.

Some of the major features include

Standard plugins

Mesh modification API

IDE

Built-in Terrain, Ocean and animation editor

ODE physics engine support

Full lightmap control

Live preview for materials, particles, trails and HUDs

Collada exchange format support

The web edition of Shiva3d is completely free and other editions you have subscribe.

Moai SDK

Moai SDK is a cross platorm mobile game engine that supports iPhone, iPad, and Android platforms. Moai platform initially consisted of Moai SDK, an open source game engine, and Moai Cloud, a cloud platform as a service for the hosting and deployment of game services. Now the Moai Cloud is shutdown and only the game engine is available.

LOVE

LOVE is a framework that you can use to make 2D games. It is free and open-source. It supports Windows, Mac OS X and Linux platforms.

It provides multiple features which include,

Audio API

File System API

Keyboard and Joystick APIs

Math API

Window and Mouse APIs

Physics API

System and timer APIs

CryEngine

CryEngine is a game engine developed by the German game developer Crytek. It has evolved from generation 1 to generation 4 and is an advanced development solution. It supports PC, Xbox 360, PlayStation3 and WiiU games.

In Game Mixing & Profiling, Data-driven Sound System Dynamic Sounds & Interactive Music and so on.

Physics features like Procedural Deformation and Advanced Rope Physics

An Ending Note

Each of these Game SDKs/frameworks have their own advantages and disadvantages. A proper choice between them makes your task easier and you can have a better time with it. So, before using it, you need to know the requirements for your game and then analyze which satisfies all your needs and then should use them.

Lua - Standard Libraries

Lua standard libraries provides a rich set of functions that is implemented directly with the C API and is in built with Lua programming language. These libraries provides services within the Lua programming language and also provides outside services like file and db operations.

These standard libraries built in official C API are provided as separate C modules. This includes,

Basic library, which includes the coroutine sub-library

Modules library

String manipulation

Table manipulation

Math library

File Input and output

Operating system facilities

Debug facilities

Basic library

We have used the basic library throughtout the tutorial under various topics. The following table provides links of related pages and lists the funtions that are covered in various part of this Lua tutorial

It opens the file and executes the contents of the file as a chunk. If no parameter is passed, then this function executes the contents of standard input. The errors will be propagated to the caller.

4.

_G

Thus is the global variable that holds the global environment (that is, _G._G = _G). Lua itself does not use this variable.

5.

getfenv ([f])

Returns the current environment in use by the function. f can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function calling getfenv. If the given function is not a Lua function, or if f is 0, getfenv returns the global environment. The default for f is 1.

6.

getmetatable (object)

If object does not have a metatable, returns nil. Otherwise, if the object's metatable has a "__metatable" field, returns the associated value. Otherwise, returns the metatable of the given object.

7.

ipairs (t)

This functions fetches the indices and values of tables.

8.

load (func [, chunkname])

Loads a chunk using function func to get its pieces. Each call to func must return a string that concatenates with previous results.

9.

loadfile ([filename]))

Similar to load, but gets the chunk from file filename or from the standard input, if no file name is given.

10.

loadstring (string [, chunkname])

Similar to load, but gets the chunk from the given string.

11.

next (table [, index])

Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next returns the next index of the table and its associated value.

12.

pairs (t)

Suspends the running coroutine. The parameter passed to this method acts as additional return values to the resume function.

13.

print (...)

Suspends the running coroutine. The parameter passed to this method acts as additional return values to the resume function.

14.

rawequal (v1, v2)

Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean.

15.

rawget (table, index)

Gets the real value of table[index], without invoking any metamethod. table must be a table; index may be any value.

16.

rawset (table, index, value)

Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index any value different from nil, and value any Lua value. This function returns table.

17.

select (index, ...)

If index is a number, returns all arguments after argument number index. Otherwise, index must be the string "#", and select returns the total number of extra arguments it received.

18.

setfenv (f, table)

Sets the environment to be used by the given function. f can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function calling setfenv. setfenv returns the given function. As a special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns no values.

19.

setmetatable (table, metatable)

Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from C.) If metatable is nil, removes the metatable of the given table. If the original metatable has a "__metatable" field, raises an error. This function returns table.

20.

tonumber (e [, base])

Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns this number; otherwise, it returns nil.

21.

tostring (e)

Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, use string.format.

22.

type (v)

Returns the type of its only argument, coded as a string. The possible results of this function are "nil" (a string, not the value nil), "number", "string", "boolean", "table", "function", "thread", and "userdata".

23.

unpack (list [, i [, j]])

Returns the elements from the given table.

24.

_VERSION

A global variable (not a function) that holds a string containing the current interpreter version. The current contents of this variable is "Lua 5.1".

Modules Library

The modules library provides the basic functions for loading modules in Lua. It exports one function directly in the global environment: require. Everything else is exported in a table package. The details about the modules library is explained in the earlier chapter Lua - Modules tutorial.

String manipulation

Lua provides a rich set of string manipulation functions. The earlier Lua - Strings tutorial covers this in detail.

Table manipulation

Lua depends on tables in almost every bit of its operations. The earlier Lua - Tables tutorial covers this in detail.

Math library

In any programming language, mathematical functions are often required to do various scientific and engineering calculations. These functions are explained in Lua - Math library tutorial.

File Input and output

We often need data storage facility in programming and this is provided by standard library functions for file I/O in Lua. It is discussed in earlier Lua - File I/O tutorial.