Lua – Web Programming ”; Previous Next Lua is a highly flexible language and it is often used in multiple platforms including web applications. The Kepler community that was formed in 2004 to provide open source web components in Lua. Even though, there are other web frameworks using Lua that have been developed, we will be primarily focusing on the 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 its installation and usage, refer kepler the 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, you need to install LuaRocks first. If you haven”t installed all the dependencies, here are the steps to be followed to setup Orbit in Unix/Linux environment. Installing Apache Connect to your server. Install Apache2, its support modules and enable required Apache2 modules using − $ sudo apt-get install apache2 libapache2-mod-fcgid libfcgi-dev build-essential $ sudo a2enmod rewrite $ sudo a2enmod fcgid $ sudo /etc/init.d/apache2 force-reload Install LuaRocks $ sudo apt-get install luarocks Install WSAPI, FCGI, Orbit, and Xavante $ sudo luarocks install orbit $ sudo luarocks install wsapi-xavante $ sudo luarocks install wsapi-fcgi 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 an ”AllowOverride None” then you need to change the ”None” to ”All” so that the .htaccess file can override the configuration locally. <IfModule mod_fcgid.c> AddHandler fcgid-script .lua AddHandler fcgid-script .ws AddHandler fcgid-script .op FCGIWrapper “/usr/local/bin/wsapi.fcgi” .ws FCGIWrapper “/usr/local/bin/wsapi.fcgi” .lua FCGIWrapper “/usr/local/bin/op.fcgi” .op #FCGIServer “/usr/local/bin/wsapi.fcgi” -idle-timeout 60 -processes 1 #IdleTimeout 60 #ProcessLifeTime 60 </IfModule> Restart the server to ensure the changes made comes into effect. To enable your application, you need to add +ExecCGI to an .htaccess file in the root of your Orbit application − in this case, /var/www. Options +ExecCGI DirectoryIndex index.ws Simple Example − Orbit #!/usr/bin/env index.lua — index.lua require”orbit” — declaration module(“myorbit”, package.seeall, orbit.new) — handler function index(web) return my_home_page() end — dispatch myorbit:dispatch_get(index, “/”, “/index”) — Sample page function my_home_page() return [[ <head></head> <html> <h2>First Page</h2> </html> ]] end Now, you should be able to launch your web browser. Go to http://localhost:8080/ and you should see the following output − First Page Orbit provides another option, i.e., Lua code can generate html. #!/usr/bin/env index.lua — index.lua require”orbit” function generate() return html { head{title “HTML Example”}, body{ h2{“Here we go again!”} } } end orbit.htmlify(generate) print(generate()) Creating Forms A simple form example is shown below − #!/usr/bin/env index.lua require”orbit” function wrap (inner) return html{ head(), body(inner) } end function test () return wrap(form (H”table” { tr{td”First name”,td( input{type = ”text”, name=”first”})}, tr{td”Second name”,td(input{type = ”text”, name=”second”})}, tr{ td(input{type = ”submit”, value = ”Submit!”}), td(input{type = ”submit”,value = ”Cancel”}) }, })) end orbit.htmlify(wrap,test) print(test()) WSAPI As mentioned earlier, WSAPI acts as the base for many projects and have multiple features embedded in it. You can use WSAPI and support the following platforms, Windows UNIX-based systems The supported servers and interfaces by WSAPI includes, CGI FastCGI Xavante WSAPI provides a number of libraries, which makes it easier for us in web programming using Lua. Some of the supported features in Lua includes, Request processing Output buffering Authentication File uploads Request isolation Multiplexing A simple example of WSAPI is shown below − #!/usr/bin/env wsapi.cgi module(…, package.seeall) function run(wsapi_env) local headers = { [“Content-type”] = “text/html” } local function hello_text() coroutine.yield(“<html><body>”) coroutine.yield(“<p>Hello Wsapi!</p>”) coroutine.yield(“<p>PATH_INFO: ” .. wsapi_env.PATH_INFO .. “</p>”) coroutine.yield(“<p>SCRIPT_NAME: ” .. wsapi_env.SCRIPT_NAME .. “</p>”) coroutine.yield(“</body></html>”) end return 200, headers, coroutine.wrap(hello_text) end 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 enables URI remapping and WSAPI handler for handing with WSAPI applications. A simple example is shown below. require “xavante.filehandler” require “xavante.cgiluahandler” require “xavante.redirecthandler” — Define here where Xavante HTTP documents scripts are located local webDir = XAVANTE_WEB local simplerules = { { — URI remapping example match = “^[^%./]*/$”, with = xavante.redirecthandler, params = {“index.lp”} }, { — cgiluahandler example match = {“%.lp$”, “%.lp/.*$”, “%.lua$”, “%.lua/.*$” }, with = xavante.cgiluahandler.makeHandler (webDir) }, { — filehandler example match = “.”, with = xavante.filehandler, params = {baseDir = webDir} }, } xavante.HTTP{ server = {host = “*”, port = 8080}, defaultHost = { rules = simplerules }, } To use virtual hosts with Xavante, the call to xavante.HTTP would be changed to something like as follows − xavante.HTTP{ server = {host = “*”, port = 8080}, defaultHost = {}, virtualhosts = { [“www.sitename.com”] = simplerules } } Lua Web Components Copas, a dispatcher based on coroutines that can be used by TCP/IP servers. Cosmo,
Category: Computer Programming
Lua – Debugging
Lua – Debugging ”; Previous Next 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. Sr.No. 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 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. 10 sethook(optional thread, hook function, hook mask string with “c” and/or “r” and/or “l”, optional instruction count) Sets the given function as a hook. The string mask and the number count describes 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 to the local variable with index local of the function at 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 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. 14 traceback(optional thread, optional message string, optional level argument) Builds an extended error message with a traceback. 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. Live Demo function myfunction () print(debug.traceback(“Stack trace”)) print(debug.getinfo(1)) print(“Stack trace end”) return 10 end myfunction () print(debug.getinfo(1)) When we run the above program, we will get the stack trace as shown below. Stack trace stack traceback: test2.lua:2: in function ”myfunction” test2.lua:8: in main chunk [C]: ? table: 0054C6C8 Stack trace end 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. Debugging – Example We often 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. Live Demo function newCounter () local n = 0 local k = 0 return function () k = n n = n + 1 return n end end counter = newCounter () print(counter()) print(counter()) local i = 1 repeat name, val = debug.getupvalue(counter, i) if name then print (“index”, i, name, “=”, val) if(name == “n”) then debug.setupvalue (counter,2,10) end i = i + 1 end — if until not name print(counter()) When we run the above program, we will get the following output. 1 2 index 1 k = 1 index 2 n = 2 11 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.
Lua – Metatables
Lua – Metatables ”; Previous Next 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. Let”s 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. Live Demo mytable = setmetatable({key1 = “value1”}, { __index = function(mytable, key) if key == “key2” then return “metatablevalue” else return nil end end }) print(mytable.key1, mytable.key2) When we run the above program, we will get the following output. value1 metatablevalue Let us explain what happened in the above example in steps. The table mytable here is {key1 = “value1”}. Metatable is set for mytable that contains a function for __index, which we call as a metamethod. The metamethod does a simple job of looking up for an index “key2″, if it”s found, it returns “metatablevalue”, otherwise returns mytable”s value for corresponding index. We can have a simplified version of the above program as shown below. mytable = setmetatable({key1 = “value1”}, { __index = { key2 = “metatablevalue” } }) print(mytable.key1,mytable.key2) __newindex When we add __newindex to metatable, if keys are not available in the table, the behavior of new keys will be defined by meta methods. A simple example where metatable”s index is set when index is not available in the main table is given below. Live Demo mymetatable = {} mytable = setmetatable({key1 = “value1”}, { __newindex = mymetatable }) print(mytable.key1) mytable.newkey = “new value 2” print(mytable.newkey,mymetatable.newkey) mytable.key1 = “new value 1” print(mytable.key1,mymetatable.newkey1) When you run the above program, you get the following output. value1 nil new value 2 new value 1 nil You can see in the above program, if a key exists in the main table, it just updates it. When a key is not available in the maintable, it adds that key to the metatable. Another example that updates the same table using rawset function is shown below. Live Demo mytable = setmetatable({key1 = “value1”}, { __newindex = function(mytable, key, value) rawset(mytable, key, “””..value..”””) end }) mytable.key1 = “new value” mytable.key2 = 4 print(mytable.key1,mytable.key2) When we run the above program we will get the following output. new value “4” rawset sets value without using __newindex of metatable. Similarly there is rawget that gets value without using __index. Adding Operator Behavior to Tables A simple example to combine two tables using + operator is shown below − Live Demo mytable = setmetatable({ 1, 2, 3 }, { __add = function(mytable, newtable) for i = 1, table.maxn(newtable) do table.insert(mytable, table.maxn(mytable)+1,newtable[i]) end return mytable end }) secondtable = {4,5,6} mytable = mytable + secondtable for k,v in ipairs(mytable) do print(k,v) end When we run the above program, we will get the following output. 1 1 2 2 3 3 4 4 5 5 6 6 The __add key is included in the metatable to add behavior of operator +. The table of keys and corresponding operator is shown below. Sr.No. Mode & Description 1 __add Changes the behavior of operator ”+”. 2 __sub Changes the behavior of operator ”-”. 3 __mul Changes the behavior of operator ”*”. 4 __div Changes the behavior of operator ”/”. 5 __mod Changes the behavior of operator ”%”. 6 __unm Changes the behavior of operator ”-”. 7 __concat Changes the behavior of operator ”..”. 8 __eq Changes the behavior of operator ”==”. 9 __lt Changes the behavior of operator ”<”. 10 __le Changes the behavior of operator ”<=”. __call Adding behavior of method call is done using __call statement. A simple example that returns the sum of values in main table with the passed table. Live Demo mytable = setmetatable({10}, { __call = function(mytable, newtable) sum = 0 for i = 1, table.maxn(mytable) do sum = sum + mytable[i] end for i = 1, table.maxn(newtable) do sum = sum + newtable[i] end return sum end }) newtable = {10,20,30} print(mytable(newtable)) When we run the above program, we will get the following output. 70 __tostring To change the behavior of the print statement, we can use the __tostring metamethod. A simple example is shown below. Live Demo mytable = setmetatable({ 10, 20, 30 }, { __tostring = function(mytable) sum = 0 for k, v in pairs(mytable) do sum = sum + v end return “The sum of values in the table is ” .. sum end }) print(mytable) When we run the above program, we will get the following output. The sum of values in the table is 60 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. Print Page Previous Next Advertisements ”;
Lua – Tables
Lua – Tables ”; Previous Next 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 the 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 known that there is no fixed relationship between a variable that holds reference of table and the table itself. –sample table initialization mytable = {} –simple table value assignment mytable[1]= “Lua” –removing reference mytable = nil — lua garbage collection will take care of releasing memory 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. — Simple empty table mytable = {} print(“Type of mytable is “,type(mytable)) mytable[1]= “Lua” mytable[“wow”] = “Tutorial” print(“mytable Element at index 1 is “, mytable[1]) print(“mytable Element at index wow is “, mytable[“wow”]) — alternatetable and mytable refers to same table alternatetable = mytable print(“alternatetable Element at index 1 is “, alternatetable[1]) print(“alternatetable Element at index wow is “, alternatetable[“wow”]) alternatetable[“wow”] = “I changed it” print(“mytable Element at index wow is “, mytable[“wow”]) — only variable released and and not table alternatetable = nil print(“alternatetable is “, alternatetable) — mytable is still accessible print(“mytable Element at index wow is “, mytable[“wow”]) mytable = nil print(“mytable is “, mytable) When we run the above program we will get the following output − 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 alternatetable 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. Sr.No. 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 us see some samples of the above functions. Table Concatenation We can use the concat function to concatenate two tables as shown below − Live Demo fruits = {“banana”,”orange”,”apple”} — returns concatenated string of table print(“Concatenated string “,table.concat(fruits)) –concatenate with a character print(“Concatenated string “,table.concat(fruits,”, “)) –concatenate fruits based on index print(“Concatenated string “,table.concat(fruits,”, “, 2,3)) When we run the above program we will get the following output − Concatenated string bananaorangeapple Concatenated string banana, orange, apple Concatenated string orange, apple Insert and Remove Insertion and removal of items in tables is most common in table manipulation. It is explained below. Live Demo fruits = {“banana”,”orange”,”apple”} — insert a fruit at the end table.insert(fruits,”mango”) print(“Fruit at index 4 is “,fruits[4]) –insert fruit at index 2 table.insert(fruits,2,”grapes”) print(“Fruit at index 2 is “,fruits[2]) print(“The maximum elements in table is”,table.maxn(fruits)) print(“The last element is”,fruits[5]) table.remove(fruits) print(“The previous last element is”,fruits[5]) When we run the above program, we will get the following output − Fruit at index 4 is mango Fruit at index 2 is grapes The maximum elements in table is 5 The last element is mango The previous last element is nil Sorting Tables We often require to sort a table in a particular order. The sort functions sort the elements in a table alphabetically. A sample for this is shown below. Live Demo fruits = {“banana”,”orange”,”apple”,”grapes”} for k,v in ipairs(fruits) do print(k,v) end table.sort(fruits) print(“sorted table”) for k,v in ipairs(fruits) do print(k,v) end When we run the above program we will get the following output − 1 banana 2 orange 3 apple 4 grapes sorted table 1 apple 2 banana 3 grapes 4 orange Print Page Previous Next Advertisements ”;
Logo – Arithmetic Operators
Logo – Arithmetic Operations ”; Previous Next Logo provides the usual arithmetic operations of addition, subtraction, multiplication and division, denoted by the symbols +, -, *, /. Each of these operations produces a result. If you don”t do something with the result, such as print it, Logo will show an error. With the print command, the result of an arithmetic operation can be used and printed in the command window. Examples given in the following screenshot demonstrate the same. Other useful commands are − sqrt − It takes one non-negative argument and returns its square root. power − It takes two arguments, call them ‘a’ and ‘b’, and generates a to the b power. ln − It takes one argument and returns its natural logarithm. exp − It takes one argument and computes e to that power, e is the natural number 2.718281828. log10 − It takes the logarithm to base 10 of its one argument. Following screenshot shows an example of the above commands with their respective output. Arithmetic operators have a precedence that determines the order with which they are evaluated. Note − print 60 * sqrt 2 and print sqrt 2 * 60 produce different answers. Here the * operator has a precedence over the sqrt operator. Thus, * will be done before sqrt, if there is a choice, as there is in the second case. For this reason, the first statement prints the value of 60 times the square root of 2, whereas the second statement prints the square root of 120 as shown in the following screenshot. Print Page Previous Next Advertisements ”;
Lua – Decision Making
Lua – Decision Making ”; Previous Next Decision making structures require that the programmer specifies 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 the following types of decision making statements. Sr.No. Statement & Description 1 if statement An if statement consists of a boolean expression followed by one or more statements. 2 if…else statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false. 3 nested if statements You can use one if or else if statement inside another if or else if statement(s). Print Page Previous Next Advertisements ”;
Lua – Environment
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 ”;
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 ”;