Lua – Environment ”; Previous Next Local Environment Setup If you are still willing to set up your environment for Lua programming language, you need the following softwares available on your computer – (a) Text Editor, (b) The Lua Interpreter, and (c) Lua Compiler. Text Editor You need a text editor to type your program. Examples of a few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of the 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 these files contain the program source code. The source files for Lua programs are typically named with the extension “.lua”. The Lua Interpreter It is just a small program that enables you to type Lua commands and have them executed immediately. It stops the execution of a Lua file in case it encounters an error unlike a compiler that executes fully. The Lua Compiler When we extend Lua to other languages/applications, we need a Software Development Kit with a compiler that is compatible with the Lua Application Program Interface. Installation on Windows There is a separate IDE named “SciTE” developed for the windows environment, which can be downloaded from https://code.google.com/p/luaforwindows/ download section. Run the downloaded executable to install the Lua IDE. Since it’s an IDE, you can both create and build the Lua code using the same. In case, you are interested in installing Lua in command line mode, you need to install MinGW or Cygwin and then compile and install Lua in windows. Installation on Linux To download and build Lua, use the following command − $ wget http://www.lua.org/ftp/lua-5.2.3.tar.gz $ tar zxf lua-5.2.3.tar.gz $ cd lua-5.2.3 $ make linux test In order to install on other platforms like aix, ansi, bsd, generic linux, mingw, posix, solaris by replacing Linux in make Linux, test with the corresponding platform name. We have a helloWorld.lua, in Lua as follows − print(“Hello World!”) Now, we can build and run a Lua file say helloWorld.lua, by switching to the folder containing the file using cd, and then using the following command − $ lua helloWorld We can see the following output. Hello World! Installation on Mac OS X To build/test Lua in the Mac OS X, use the following command − $ curl -R -O http://www.lua.org/ftp/lua-5.2.3.tar.gz $ tar zxf lua-5.2.3.tar.gz $ cd lua-5.2.3 $ make macosx test In certain cases, you may not have installed the Xcode and command line tools. In such cases, you won’t 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, in Lua, as follows − print(“Hello World!”) Now, we can build and run a Lua file say helloWorld.lua by switching to the 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 the default IDE provided by the Lua creator team. The alternate IDE available is from ZeroBrane Studio, which is available across multiple platforms like Windows, Mac and Linux. There are also plugins for eclipse that enable the 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. Print Page Previous Next Advertisements ”;
Category: lua
Lua – Error Handling
Lua – Error Handling ”; Previous Next Need for Error Handling Error handling is quite critical since real-world operations often require the use of complex operations, which includes file operations, database transactions and web service calls. 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 a difference between the use of a single “equal to” and double “equal to”. Using one instead of the other can lead to an error. One “equal to” refers to assignment while a double “equal to” refers to comparison. Similarly, we have expressions and functions having their predefined ways of implementation. Another example for syntax error is shown below − Live Demo 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 handle 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 runtime errors due to mistakes in input or mishandled functions. A simple example to show run time error is shown below. Live Demo function add(a,b) return a+b end add(10) When we build the program, it will build successfully and run. Once it runs, shows a run time error. lua: test2.lua:2: attempt to perform arithmetic on local ”b” (a nil value) stack traceback: test2.lua:2: in function ”add” test2.lua:5: in main chunk [C]: ? This is a runtime 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 errors, we often use two functions − assert and error. A simple example is shown below. Live Demo 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. Live Demo function myfunction () n = n/nil end if pcall(myfunction) then print(“Success”) else print(“Failure”) end When we run the above program, we will get the following output. Failure 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. A simple example for xpcall is shown below. Live Demo function myfunction () n = n/nil end function myerrorhandler( err ) print( “ERROR:”, err ) end status = xpcall( myfunction, myerrorhandler ) print( status) When we run the above program, we will get the following output. ERROR: test2.lua:2: attempt to perform arithmetic on global ”n” (a nil value) false 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. Print Page Previous Next Advertisements ”;
Lua – Iterators
Lua – Iterators ”; Previous Next 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. Live Demo array = {“Lua”, “Tutorial”} for key,value in ipairs(array) do print(key, value) end When we run the above code, we will get the following output − 1 Lua 2 Tutorial The above example uses the default ipairs iterator function provided by Lua. 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 does not 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. Live Demo 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. Live Demo 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. Live Demo 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 multiple elements for each of the time we iterate through the collection. Print Page Previous Next Advertisements ”;
Lua – Data Types
Lua – Data Types ”; Previous Next 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. Sr.No Value Type & Description 1 nil Used to differentiate the value from having some data or no(nil) data. 2 boolean Includes true and false as values. Generally used for condition checking. 3 number Represents real(double precision floating point) numbers. 4 string Represents array of characters. 5 function Represents a method that is written in C or Lua. 6 userdata Represents arbitrary C data. 7 thread Represents independent threads of execution and it is used to implement coroutines. 8 table Represent ordinary arrays, symbol tables, sets, records, graphs, trees, etc., and implements associative arrays. It can hold any value (except nil). Type Function In Lua, there is a function called ‘type’ that enables us to know the type of the variable. Some examples are given in the following code. Live Demo print(type(“What is my type”)) –> string t = 10 print(type(5.8*t)) –> number print(type(true)) –> boolean print(type(print)) –> function print(type(nil)) –> nil print(type(type(ABC))) –> string When you build and execute the above program, it produces the following result on Linux − string number boolean function nil string By default, all the variables will point to nil until they are assigned a value or initialized. 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. Print Page Previous Next Advertisements ”;
Lua – Arrays
Lua – Arrays ”; Previous Next Arrays are ordered arrangement of objects, which may be a one-dimensional array containing a collection of rows or a multi-dimensional array containing multiple rows and columns. In Lua, arrays are implemented using indexing tables with integers. The size of an array is not fixed and it can grow based on our requirements, subject to memory constraints. One-Dimensional Array A one-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. Live Demo 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. Live Demo 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 will get the following output. -4 -2 0 2 4 Multi-Dimensional Array Multi-dimensional arrays can be implemented in two ways. Array of arrays Single dimensional array by manipulating indices An example for multidimensional array of 3. 3 is shown below using array of arrays. Live Demo — 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 will get the following output. 1 2 3 2 4 6 3 6 9 An example for multidimensional array is shown below using manipulating indices. Live Demo — 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 will 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 implementation 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. Print Page Previous Next Advertisements ”;
Lua – Home
Lua Tutorial Job Search PDF Version Quick Guide Resources Discussion This Lua tutorial lets you explore a new language, Lua. This tutorial has everything from fundamentals of the programming language to advanced concepts. After completing this tutorial, you will find yourself good with programming using Lua. What is Lua? Lua is an open source language built on top of C programming language. It is exclusively designed for embedded systems. It features dynamic typing, simple syntax and efficient memory management. Lua has its value across multiple platforms ranging from large server systems to small mobile applications. The name “Lua” means ”Moon” in Portuguese. We should write as “Lua” not “LUA” because LUA can have different meanings for different people and confusing also. Why Choose Lua? Lua is free open-source software, known especially for game development. Some key features which makes Lua a popular choice are − Syntax of Lua is simple and minimal which makes it easy to learn. Lua uses dynamic typing, where we can assign any value to a variable without explicit type declaration. Lua can integrate with other programming languages and systems, which is used in multi-language projects. Lua is fast in terms of performance. Lua is portable i.e, runs perfectly on all platforms that has a standard C compiler like embedded processors, mobile devices and windows. Jobs & Opportunities Well , learning only Lua wouldn”t help you get any job but Lua is quite an important tool to be skilled in if an individual is looking for these jobs − Game Developers Embedded systems developer Gameplay Programmer Software Developer Lua- Scripted video games Lua programming language is popularly used for scripting video games, as it relatively eases the process of embedding and deploying. Some notable games that use Lua are − World of Warcraft ROBLOX Angry Birds Prerequisites to Learn Lua You don”t have to know a lot of Prerequisites to learn Lua. However, knowledge on fundamental topics would make the process easy. Understanding basic programming concepts, scripting concepts and development environment would help even if you are a total beginner. Additionally, start the learning process with tutorials and explore sample codes. Who Should Learn Lua? This tutorial is designed for all those readers who are looking for a starting point to learn Lua. It has topics suitable for both beginners as well as advanced users. Frequently Asked Questions about Lua There are some important frequently asked questions (FAQs) about Lua, this section lists them down along with their answers briefly − What is Lua and where is it commonly used? Lua is a lightweight, embeddable scripting language. It”s often used in game development, web applications, embedded systems, and as a configuration language. Is Lua object-oriented? Lua supports object-oriented programming through tables and metatables, but it doesn”t have classes in the traditional sense. Is Lua a compiled or interpreted language? Lua is typically interpreted, but it can also be compiled into bytecode for performance optimization. What are the basic data types in Lua? Lua supports numbers, strings, booleans, nil, tables, functions, and userdata. What is the role of metatables in Lua? Metatables allow you to customize the behavior of Lua tables, enabling features like operator overloading and metamethods. Why is Lua popular in game development? Lua”s simplicity, fast execution, and embeddability make it a suitable choice for scripting game logic, AI, and user interfaces. What are some popular game engines that use Lua? Unity, Roblox, and World of Warcraft are notable examples of game engines that utilize Lua. How does Lua compare to other scripting languages in terms of performance? Lua is generally considered a fast scripting language, often outperforming other scripting languages in benchmarks. How can I get started with Lua? Follow this tutorial chapter-wise for a complete understanding about Lua programming. Start Lua by installing Lua, writing basic scripts, and exploring its core concepts like variables, data types, control flow, and functions. Print Page Previous Next Advertisements ”;
Lua – Overview
Lua – Overview ”; Previous Next Lua is an extensible, lightweight 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 be integrated with the 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 at: 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 two parts – the Lua interpreter part and the functioning software system. The functioning software system 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 high-end network servers to small devices. Both Lua”s language and its interpreter are mature, small, and fast. It has evolved from 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 point while learning Lua is to focus on the concepts without getting lost in its technical details. The purpose of learning a programming language is to become a better programmer; that is, to become more effective in 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 add-ons for databases like MySQL Proxy and MySQL WorkBench Security systems like Intrusion Detection System. Print Page Previous Next Advertisements ”;
Lua – Loops
Lua – Loops ”; Previous Next 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. Following is the general form of a loop statement in most of the programming languages − Lua provides the following types of loops to handle looping requirements. Sr.No. Loop Type & Description 1 while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 3 repeat…until loop Repeats the operation of group of statements till the until condition is met. 4 nested loops You can use one or more loop inside any another while, for or do..while loop. Loop Control Statement Loop control statement changes execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Lua supports the following control statements. Sr.No. Control Statement & Description 1 break statement 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 forever. We can use the break statement to break this loop. while( true ) do print(“This loop will run forever.”) end Print Page Previous Next Advertisements ”;
Lua – Database Access
Lua – Database Access ”; Previous Next 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, we 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”. You have created a database test. You have gone through MySQL tutorial to understand MySQL Basics. Importing MySQL We can use a simple require statement to import the sqlite library assuming that your Lua implementation was done correctly. 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 a MySQL environment and then creating a connection for the environment. It is shown below. local env = mysql.mysql() local conn = env:connect(”test”,”root”,”123456”) The above connection will connect to an existing MySQL 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([[ ”MySQLSTATEMENT” ]]) In the above syntax, we need to ensure that conn is open and existing MySQL connection and replace the ”MySQLSTATEMENT” 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. mysql = require “luasql.mysql” local env = mysql.mysql() local conn = env:connect(”test”,”root”,”123456”) print(env,conn) status,errorString = conn:execute([[CREATE TABLE sample2 (id INTEGER, name TEXT);]]) print(status,errorString ) 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 an 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. cursor,errorString = conn:execute([[select * from sample]]) row = cursor:fetch ({}, “a”) while row do print(string.format(“Id: %s, Name: %s”, row.id, row.name)) — reusing the table of results row = cursor:fetch (row, “a”) end In the above code, conn is an open MySQL connection. With the help of the cursor returned by the execute statement, you can loop through the table response and fetch the required select data. A Complete Example A complete example including all the above statements is given below. mysql = require “luasql.mysql” local env = mysql.mysql() local conn = env:connect(”test”,”root”,”123456”) print(env,conn) status,errorString = conn:execute([[CREATE TABLE sample3 (id INTEGER, name TEXT)]]) print(status,errorString ) status,errorString = conn:execute([[INSERT INTO sample3 values(”12”,”Raj”)]]) print(status,errorString ) cursor,errorString = conn:execute([[select * from sample3]]) print(cursor,errorString) row = cursor:fetch ({}, “a”) while row do print(string.format(“Id: %s, Name: %s”, row.id, row.name)) row = cursor:fetch (row, “a”) end — close everything cursor:close() conn:close() env:close() When you run the above program, you will get the following output. MySQL environment (0037B178) MySQL connection (0037EBA8) 0 nil 1 nil MySQL cursor (003778A8) nil Id: 12, Name: Raj 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 In order to initiate a transaction, we need to execute the following statement in Lua, assuming conn is an open MySQL connection. conn:execute([[START TRANSACTION;]]) Rollback Transaction We need to execute the following statement to rollback changes made after start transaction is executed. conn:execute([[ROLLBACK;]]) Commit Transaction We need to 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
Lua – Object Oriented
Lua – Object Oriented ”; Previous Next Introduction to OOP Object Oriented Programming (OOP), is one the most used programming technique that is 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 a rectangle with three properties area, length, and breadth is shown below. It also has a printArea function to print the area calculated. — Meta class Rectangle = {area = 0, length = 0, breadth = 0} — Derived class method new function Rectangle:new (o,length,breadth) o = o or {} setmetatable(o, self) self.__index = self self.length = length or 0 self.breadth = breadth or 0 self.area = length*breadth; return o end — Derived class method printArea function Rectangle:printArea () print(“The area of Rectangle is “,self.area) end Creating an Object Creating an 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 a 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. Complete Example Lets look at a complete example using object orientation in Lua. Live Demo — Meta class Shape = {area = 0} — Base class method new function Shape:new (o,side) o = o or {} setmetatable(o, self) self.__index = self side = side or 0 self.area = side*side; return o end — Base class method printArea function Shape:printArea () print(“The area is “,self.area) end — Creating an object myshape = Shape:new(nil,10) myshape:printArea() When you run the above program, you will get the following output. The area is 100 Inheritance in Lua Inheritance is the process of extending simple base objects like shape to rectangles, squares and so on. It is often used in the real world to share and extend the basic properties and functions. Let us see a simple class extension. We have a class as shown below. — Meta class Shape = {area = 0} — Base class method new function Shape:new (o,side) o = o or {} setmetatable(o, self) self.__index = self side = side or 0 self.area = side*side; return o end — Base class method printArea function Shape:printArea () print(“The area is “,self.area) end We can extend the shape to a square class as shown below. Square = Shape:new() — Derived class method new function Square:new (o,side) o = o or Shape:new(o,side) setmetatable(o, self) self.__index = self return o end Over-riding Base Functions We can override the base class functions that is instead of using the function in the base class, derived class can have its own implementation as shown below − — Derived class method printArea function Square:printArea () print(“The area of square is “,self.area) end Inheritance Complete Example We can extend the simple class implementation in Lua as shown above with the help of another new method with the help of metatables. All the member variables and functions of base class are retained in the derived class. Live Demo — Meta class Shape = {area = 0} — Base class method new function Shape:new (o,side) o = o or {} setmetatable(o, self) self.__index = self side = side or 0 self.area = side*side; return o end — Base class method printArea function Shape:printArea () print(“The area is “,self.area) end — Creating an object myshape = Shape:new(nil,10) myshape:printArea() Square = Shape:new() — Derived class method new function Square:new (o,side) o = o or Shape:new(o,side) setmetatable(o, self) self.__index = self return o end — Derived class method printArea function Square:printArea () print(“The area of square is “,self.area) end — Creating an object mysquare = Square:new(nil,10) mysquare:printArea() Rectangle = Shape:new() — Derived class method new function