Lua – Math library ”; Previous Next We often need math operations in scientific and engineering calculations and we can avail this using the standard Lua library math. The list of functions available in math library is shown in the following table. Sr.No. Library / Method & Purpose 1 math.abs (x) Returns the absolute value of x. 2 math.acos (x) Returns the arc cosine of x (in radians). 3 math.asin (x) Returns the arc sine of x (in radians). 4 math.atan (x) Returns the arc tangent of x (in radians). 5 math.atan2 (y, x) Returns the arc tangent of y/x (in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of x being zero.) 6 math.ceil (x) Returns the smallest integer larger than or equal to x. 7 math.cos (x) Returns the cosine of x (assumed to be in radians). 8 math.cosh (x) Returns the hyperbolic cosine of x. 9 math.deg (x) Returns the angle x (given in radians) in degrees. 10 math.exp (x) Returns the value e power x. 11 math.floor (x) Returns the largest integer smaller than or equal to x. 12 math.fmod (x, y) Returns the remainder of the division of x by y that rounds the quotient towards zero. 13 math.frexp (x) Returns m and e such that x = m2e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero). 14 math.huge The value HUGE_VAL, a value larger than or equal to any other numerical valu. 15 math.ldexp (m, e) Returns m2e (e should be an integer). 16 math.log (x) Returns the natural logarithm of x. 17 math.log10 (x) Returns the base-10 logarithm of x. 18 math.max (x, …) Returns the maximum value among its arguments. 19 math.min (x, …) Returns the minimum value among its arguments. 20 math.modf (x) Returns two numbers, the integral part of x and the fractional part of x. 21 math.pi The value of pi. 22 math.pow (x, y) Returns xy. (You can also use the expression x^y to compute this value.) 23 math.rad (x) Returns the angle x (given in degrees) in radians. 24 math.random ([m [, n]]) This function is an interface to the simple pseudo-random generator function rand provided by ANSI C.When called without arguments, returns a uniform pseudo-random real number in the range [0,1). When called with an integer number m, math.random returns a uniform pseudo-random integer in the range [1, m]. When called with two integer numbers m and n, math.random returns a uniform pseudo-random integer in the range [m, n]. 25 math.randomseed (x) Sets x as the “seed” for the pseudo-random generator: equal seeds produce equal sequences of numbers. 26 math.sin (x) Returns the sine of x (assumed to be in radians). 27 math.sinh (x) Returns the hyperbolic sine of x. 28 math.sqrt (x) Returns the square root of x. (You can also use the expression x^0.5 to compute this value.) 29 math.tan (x) Returns the tangent of x (assumed to be in radians). 30 math.tanh (x) Returns the hyperbolic tangent of x. Trigonometric functions A simple example using trigonometric function is shown below. Live Demo radianVal = math.rad(math.pi / 2) io.write(radianVal,”n”) — Sin value of 90(math.pi / 2) degrees io.write(string.format(“%.1f “, math.sin(radianVal)),”n”) — Cos value of 90(math.pi / 2) degrees io.write(string.format(“%.1f “, math.cos(radianVal)),”n”) — Tan value of 90(math.pi / 2) degrees io.write(string.format(“%.1f “, math.tan(radianVal)),”n”) — Cosh value of 90(math.pi / 2) degrees io.write(string.format(“%.1f “, math.cosh(radianVal)),”n”) — Pi Value in degrees io.write(math.deg(math.pi),”n”) When we run the above program, we will get the following output. 0.027415567780804 0.0 1.0 0.0 1.0 180 Other common math functions A simple example using common math functions is shown below. Live Demo — Floor io.write(“Floor of 10.5055 is “, math.floor(10.5055),”n”) — Ceil io.write(“Ceil of 10.5055 is “, math.ceil(10.5055),”n”) — Square root io.write(“Square root of 16 is “,math.sqrt(16),”n”) — Power io.write(“10 power 2 is “,math.pow(10,2),”n”) io.write(“100 power 0.5 is “,math.pow(100,0.5),”n”) — Absolute io.write(“Absolute value of -10 is “,math.abs(-10),”n”) –Random math.randomseed(os.time()) io.write(“Random number between 1 and 100 is “,math.random(),”n”) –Random between 1 to 100 io.write(“Random number between 1 and 100 is “,math.random(1,100),”n”) –Max io.write(“Maximum in the input array is “,math.max(1,100,101,99,999),”n”) –Min io.write(“Minimum in the input array is “,math.min(1,100,101,99,999),”n”) When we run the above program, we will get the following output. Floor of 10.5055 is 10 Ceil of 10.5055 is 11 Square root of 16 is 4 10 power 2 is 100 100 power 0.5 is 10 Absolute value of -10 is 10 Random number between 1 and 100 is 0.22876674703207 Random number between 1 and 100 is 7 Maximum in the input array is 999 Minimum in the input array is 1 The above examples are just a few of the common examples, we can use math library based on our need, so try using all the functions to be more familiar. Print Page Previous Next Advertisements ”;
Category: lua
Lua – Modules
Lua – Modules ”; Previous Next What is a Module? Module is like a library that can be loaded using require and has a single global name containing a table. This module can consist of a number of functions and variables. All these functions and variables are wrapped in to the table, which acts as a namespace. Also, a well behaved module has necessary provisions to return this table on require. Specialty of Lua Modules The usage of tables in modules helps us in numerous ways and enables us to manipulate the modules in the same way we manipulate any other Lua table. As a result of the ability to manipulate modules, it provides extra features for which other languages need special mechanisms. Due to this free mechanism of modules in Lua, a user can call the functions in Lua in multiple ways. A few of them are shown below. — Assuming we have a module printFormatter — Also printFormatter has a funtion simpleFormat(arg) — Method 1 require “printFormatter” printFormatter.simpleFormat(“test”) — Method 2 local formatter = require “printFormatter” formatter.simpleFormat(“test”) — Method 3 require “printFormatter” local formatterFunction = printFormatter.simpleFormat formatterFunction(“test”) In the above sample code, you can see how flexible programming in Lua is, without any special additional code. The require Function Lua has provided a high level function called require to load all the necessary modules. It is kept as simple as possible to avoid having too much information on module to load it. The require function just assumes the modules as a chunk of code that defines some values, which is actually functions or tables containing functions. Example Let us consider a simple example, where one function has the math functions. Let”s call this module as mymath and filename being mymath.lua. The file content is as follows − local mymath = {} function mymath.add(a,b) print(a+b) end function mymath.sub(a,b) print(a-b) end function mymath.mul(a,b) print(a*b) end function mymath.div(a,b) print(a/b) end return mymath Now, in order to access this Lua module in another file, say, moduletutorial.lua, you need to use the following code segment. mymathmodule = require(“mymath”) mymathmodule.add(10,20) mymathmodule.sub(30,20) mymathmodule.mul(10,20) mymathmodule.div(30,20) In order to run this code, we need to place the two Lua files in the same directory or alternatively, you can place the module file in the package path and it needs additional setup. When we run the above program, we will get the following output. 30 10 200 1.5 Things to Remember Place both the modules and the file you run in the same directory. Module name and its file name should be the same. It is a best practice to return modules for require function and hence the module should be preferably implemented as shown above eventhough you can find other types of implementations elsewhere. Old Way of Implementing Modules Let me now rewrite the same example in the older way, which uses package.seeall type of implementation. This was used in Lua versions 5.1 and 5.0. The mymath module is shown below. module(“mymath”, package.seeall) function mymath.add(a,b) print(a+b) end function mymath.sub(a,b) print(a-b) end function mymath.mul(a,b) print(a*b) end function mymath.div(a,b) print(a/b) end The usage of modules in moduletutorial.lua is shown below. require(“mymath”) mymath.add(10,20) mymath.sub(30,20) mymath.mul(10,20) mymath.div(30,20) When we run the above, we will get the same output. But it is advised on to use the older version of the code and it is assumed to less secure. Many SDKs that use Lua for programming like Corona SDK has deprecated the use of this. Print Page Previous Next Advertisements ”;
Lua – Standard Libraries
Lua – Standard Libraries ”; Previous Next Lua standard libraries provide a rich set of functions that is implemented directly with the C API and is in-built with Lua programming language. These libraries provide services within the Lua programming language and also outside services like file and db operations. These standard libraries built in official C API are provided as separate C modules. It includes the following − Basic library, which includes the coroutine sub-library Modules library String manipulation Table manipulation Math library File Input and output Operating system facilities Debug facilities Basic Library We have used the basic library throughout the tutorial under various topics. The following table provides links of related pages and lists the functions that are covered in various part of this Lua tutorial. Sr.No. Library / Method & Purpose 1 Error Handling Includes error handling functions like assert, error as explained in Lua – Error Handling. 2 Memory Management Includes the automatic memory management functions related to garbage collection as explained in Lua – Garbage Collection. 3 dofile ([filename]) It opens the file and executes the contents of the file as a chunk. If no parameter is passed, then this function executes the contents of standard input. The errors will be propagated to the caller. 4 _G Thus is the global variable that holds the global environment (that is, _G._G = _G). Lua itself does not use this variable. 5 getfenv ([f]) Returns the current environment in use by the function. f can be a Lua function or a number that specifies the function at that stack level − Level 1 is the function calling getfenv. If the given function is not a Lua function, or if f is 0, getfenv returns the global environment. The default for f is 1. 6 getmetatable (object) If object does not have a metatable, returns nil. Otherwise, if the object”s metatable has a “__metatable” field, returns the associated value. Otherwise, returns the metatable of the given object. 7 ipairs (t) This functions fetches the indices and values of tables. 8 load (func [, chunkname]) Loads a chunk using function func to get its pieces. Each call to func must return a string that concatenates with previous results. 9 loadfile ([filename])) Similar to load, but gets the chunk from file filename or from the standard input, if no file name is given. 10 loadstring (string [, chunkname]) Similar to load, but gets the chunk from the given string. 11 next (table [, index]) Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next returns the next index of the table and its associated value. 12 pairs (t) Suspends the running coroutine. The parameter passed to this method acts as additional return values to the resume function. 13 print (…) Suspends the running coroutine. The parameter passed to this method acts as additional return values to the resume function. 14 rawequal (v1, v2) Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean. 15 rawget (table, index) Gets the real value of table[index], without invoking any metamethod. table must be a table; index may be any value. 16 rawset (table, index, value) Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index any value different from nil, and value any Lua value. This function returns table. 17 select (index, …) If index is a number, returns all arguments after argument number index. Otherwise, index must be the string “#”, and select returns the total number of extra arguments it received. 18 setfenv (f, table) Sets the environment to be used by the given function. f can be a Lua function or a number that specifies the function at that stack level − Level 1 is the function calling setfenv. setfenv returns the given function. As a special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns no values. 19 setmetatable (table, metatable) Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from C.) If metatable is nil, removes the metatable of the given table. If the original metatable has a “__metatable” field, raises an error. This function returns table. 20 tonumber (e [, base]) Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns this number; otherwise, it returns nil. 21 tostring (e) Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, use string.format. 22 type (v) Returns the type of its only argument, coded as a string. The possible results of this function are “nil” (a string, not the value nil), “number”, “string”, “boolean”, “table”, “function”, “thread”, and “userdata”. 23 unpack (list [, i [, j]]) Returns the elements from the given table. 24 _VERSION A global variable (not a function) that holds a string containing the current interpreter version. The current contents of this variable is “Lua 5.1”. 25 Coroutines Includes the coroutine manipulation functions as explained in Lua – Coroutines. Modules Library The modules library provides the basic functions for loading modules in Lua. It exports one function directly in the global environment: require. Everything else is exported in a table package. The details about the modules library is explained in the earlier chapter Lua – Modules tutorial. String manipulation Lua provides a rich set of string manipulation functions. The earlier Lua – Strings tutorial covers this in detail. Table manipulation Lua depends on tables in almost every bit of its operations. The earlier Lua – Tables tutorial covers this in detail. File Input and output We often need data storage facility in programming and this is provided by standard library functions for file I/O in
Lua – Game Programing
Lua – Game Programing ”; Previous Next Lua is used in a lot of game engines due to its simple language structure and syntax. The garbage collection feature is often quite useful in games which consume a lot of memory due to rich graphics that is used. Some game engines that use Lua includes − Corona SDK Gideros Mobile ShiVa3D Moai SDK LOVE CryEngine Each of these game engines are based on Lua and there is a rich set of API available in each of these engines. We will look at the capabilities of each in brief. Corona SDK Corona SDK is a cross platform mobile game engine that supports iPhone, iPad, and Android platforms. There is a free version of Corona SDK that can be used for small games with limited features. You can upgrade to other versions when needed. Corona SDK provides a number of features which includes the following − Physics and Collision handling APIs Web and Network APIs Game Network API Ads API Analytics API Database and File System APIs Crypto and Math APIs Audio and Media APIs It is easier and faster to develop an application using the above APIs rather than using the native APIs separately for iOS and Android. Gideros Mobile Gideros provides the cross-platform SDK to create games for iOS and Android. It is free to use with a made with Gideros splash. Some of the striking advantages in Gideoros includes, the following − Development IDE − It provides its own IDE which makes it easier to develop Gideros apps. Instant testing − While developing your game, it can be tested on a real device through Wifi in only 1 second. You don”t need to waste your time with an export or deploy process. Plugins − You can easily extend the core with plugins. Import your existing (C, C++, Java or Obj-C) code, bind to Lua and interpret them directly. Dozens of open-source plugins are already developed and ready to use. Clean OOP approach − Gideros provides its own class system with all the basic OOP standards, enabling you to write clean and reusable code for any of your future games. Native speed − Developed on top of C/C++ and OpenGL, your game runs at native speed and fully utilizes the power of CPUs and GPUs underneath. ShiVa3D ShiVa3D is one of 3D game engines which provides a graphical editor designed to create applications and video games for the Web, Consoles and Mobile devices. It supports multiple platforms which includes, Windows, Mac, Linux, iOS, Android, BlackBerry, Palm OS, Wii and WebOS. Some of the major features include Standard plugins Mesh modification API IDE Built-in Terrain, Ocean and animation editor ODE physics engine support Full lightmap control Live preview for materials, particles, trails and HUDs Collada exchange format support The web edition of Shiva3d is completely free and other editions you have subscribe. Moai SDK Moai SDK is a cross platform mobile game engine that supports iPhone, iPad, and Android platforms. Moai platform initially consisted of Moai SDK, an open source game engine, and Moai Cloud, a cloud platform as a service for the hosting and deployment of game services. Now the Moai Cloud is shutdown and only the game engine is available. Moai SDK runs on multiple platforms including iOS, Android, Chrome, Windows, Mac and Linux. LOVE LOVE is a framework that you can use to make 2D games. It is free and open-source. It supports Windows, Mac OS X and Linux platforms. It provides multiple features which include, Audio API File System API Keyboard and Joystick APIs Math API Window and Mouse APIs Physics API System and timer APIs CryEngine CryEngine is a game engine developed by the German game developer Crytek. It has evolved from generation 1 to generation 4 and is an advanced development solution. It supports PC, Xbox 360, PlayStation3 and WiiU games. It provides multiple features which include, Visual effects like Natural Lighting & Dynamic Soft Shadows, Real-time Dynamic Global Illumination, Light Propagation Volume, Particle Shading, Tessellation and so on. Character Animation System and Character Individualization System. Parametric Skeletal Animation and Unique Dedicated Facial Animation Editor AI Systems like Multi-Layer Navigation Mesh and Tactical Point System. Also provides Designer-Friendly AI Editing System. In Game Mixing & Profiling, Data-driven Sound System Dynamic Sounds & Interactive Music and so on. Physics features like Procedural Deformation and Advanced Rope Physics. An Ending Note Each of these Game SDKs/frameworks have their own advantages and disadvantages. A proper choice between them makes your task easier and you can have a better time with it. So, before using it, you need to know the requirements for your game and then analyze which satisfies all your needs and then should use them. Print Page Previous Next Advertisements ”;
Lua – Strings
Lua – Strings ”; Previous Next String is a sequence of characters as well as control characters like form feed. String can be initialized with three forms which includes − Characters between single quotes Characters between double quotes Characters between [[ and ]] An example for the above three forms are shown below. Live Demo string1 = “Lua” print(“”String 1 is””,string1) string2 = ”Tutorial” print(“String 2 is”,string2) string3 = [[“Lua Tutorial”]] print(“String 3 is”,string3) When we run the above program, we will get the following output. “String 1 is” Lua String 2 is Tutorial String 3 is “Lua Tutorial” Escape sequence characters are used in string to change the normal interpretation of characters. For example, to print double inverted commas (“”), we have used ” in the above example. The escape sequence and its use is listed below in the table. Escape Sequence Use a Bell b Backspace f Formfeed n New line r Carriage return t Tab v Vertical tab \ Backslash “ Double quotes ” Single quotes [ Left square bracket ] Right square bracket String Manipulation Lua supports string to manipulate strings − Sr.No. Method & Purpose 1 string.upper(argument) Returns a capitalized representation of the argument. 2 string.lower(argument) Returns a lower case representation of the argument. 3 string.gsub(mainString,findString,replaceString) Returns a string by replacing occurrences of findString with replaceString. 4 string.find(mainString,findString, optionalStartIndex,optionalEndIndex) Returns the start index and end index of the findString in the main string and nil if not found. 5 string.reverse(arg) Returns a string by reversing the characters of the passed string. 6 string.format(…) Returns a formatted string. 7 string.char(arg) and string.byte(arg) Returns internal numeric and character representations of input argument. 8 string.len(arg) Returns a length of the passed string. 9 string.rep(string, n)) Returns a string by repeating the same string n number times. 10 .. Thus operator concatenates two strings. Now, let”s dive into a few examples to exactly see how these string manipulation functions behave. Case Manipulation A sample code for manipulating the strings to upper and lower case is given below. Live Demo string1 = “Lua”; print(string.upper(string1)) print(string.lower(string1)) When we run the above program, we will get the following output. LUA lua Replacing a Substring A sample code for replacing occurrences of one string with another is given below. Live Demo string = “Lua Tutorial” — replacing strings newstring = string.gsub(string,”Tutorial”,”Language”) print(“The new string is “..newstring) When we run the above program, we will get the following output. The new string is Lua Language Finding and Reversing A sample code for finding the index of substring and reversing string is given below. Live Demo string = “Lua Tutorial” — replacing strings print(string.find(string,”Tutorial”)) reversedString = string.reverse(string) print(“The new string is”,reversedString) When we run the above program, we will get the following output. 5 12 The new string is lairotuT auL Formatting Strings Many times in our programming, we may need to print strings in a formatted way. You can use the string.format function to format the output as shown below. Live Demo string1 = “Lua” string2 = “Tutorial” number1 = 10 number2 = 20 — Basic string formatting print(string.format(“Basic formatting %s %s”,string1,string2)) — Date formatting date = 2; month = 1; year = 2014 print(string.format(“Date formatting %02d/%02d/%03d”, date, month, year)) — Decimal formatting print(string.format(“%.4f”,1/3)) When we run the above program, we will get the following output. Basic formatting Lua Tutorial Date formatting 02/01/2014 0.3333 Character and Byte Representations A sample code for character and byte representation, which is used for converting the string from string to internal representation and vice versa. Live Demo — Byte conversion — First character print(string.byte(“Lua”)) — Third character print(string.byte(“Lua”,3)) — first character from last print(string.byte(“Lua”,-1)) — Second character print(string.byte(“Lua”,2)) — Second character from last print(string.byte(“Lua”,-2)) — Internal Numeric ASCII Conversion print(string.char(97)) When we run the above program, we will get the following output. 76 97 97 117 117 a Other Common Functions The common string manipulations include string concatenation, finding length of string and at times repeating the same string multiple times. The example for these operations is given below. Live Demo string1 = “Lua” string2 = “Tutorial” — String Concatenations using .. print(“Concatenated string”,string1..string2) — Length of string print(“Length of string1 is “,string.len(string1)) — Repeating strings repeatedString = string.rep(string1,3) print(repeatedString) When we run the above program, we will get the following output. Concatenated string LuaTutorial Length of string1 is 3 LuaLuaLua Print Page Previous Next Advertisements ”;
Lua – Web Programming
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,
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 ”;
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 ”;