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

Lua – Functions

Lua – Functions ”; Previous Next 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 unique, 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 − optional_function_scope function function_name( argument1, argument2, argument3…….., argumentn) function_body return result_params_comma_separated end 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 of 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 − An argument is like a placeholder. When a function is invoked, you pass a value to the argument. This value is referred to as the 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 following 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 the 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 the 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 the method name and if the method returns a value, then you can store the returned value. For example − Live Demo 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 and passing a function as parameter in Lua. Live Demo myprint = function(param) print(“This is my print function – ##”,param,”##”) end function add(num1,num2,functionPrint) result = num1 + num2 functionPrint(result) end myprint(10) add(2,5,myprint) When we run the above code, we will get the following output. This is my print function – ## 10 ## This is my print function – ## 7 ## Function with Variable Argument It is possible to create functions with variable arguments in Lua using ”…” 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. Live Demo 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 Print Page Previous Next Advertisements ”;