Lua – File I/O

Lua – File I/O ”; Previous Next I/O library is used for reading and manipulating files in Lua. There are two kinds of file operations in Lua namely implicit file descriptors and explicit file descriptors. For the following examples, we will use a sample file test.lua as shown below. — sample test.lua — sample2 test.lua A simple file open operation uses the following statement. file = io.open (filename [, mode]) The various file modes are listed in the following table. Sr.No. Mode & Description 1 “r” Read-only mode and is the default mode where an existing file is opened. 2 “w” Write enabled mode that overwrites the existing file or creates a new file. 3 “a” Append mode that opens an existing file or creates a new file for appending. 4 “r+” Read and write mode for an existing file. 5 “w+” All existing data is removed if file exists or new file is created with read write permissions. 6 “a+” Append mode with read mode enabled that opens an existing file or creates a new file. Implicit File Descriptors Implicit file descriptors use the standard input/ output modes or using a single input and single output file. A sample of using implicit file descriptors is shown below. — Opens a file in read file = io.open(“test.lua”, “r”) — sets the default input file as test.lua io.input(file) — prints the first line of the file print(io.read()) — closes the open file io.close(file) — Opens a file in append mode file = io.open(“test.lua”, “a”) — sets the default output file as test.lua io.output(file) — appends a word test to the last line of the file io.write(“– End of the test.lua file”) — closes the open file io.close(file) When you run the program, you will get an output of the first line of test.lua file. For our program, we got the following output. — Sample test.lua This was the first line of the statement in test.lua file for us. Also the line “– End of the test.lua file” would be appended to the last line of the test.lua code. In the above example, you can see how the implicit descriptors work with file system using the io.”x” methods. The above example uses io.read() without the optional parameter. The optional parameter can be any of the following. Sr.No. Mode & Description 1 “*n” Reads from the current file position and returns a number if exists at the file position or returns nil. 2 “*a” Returns all the contents of file from the current file position. 3 “*l” Reads the line from the current file position, and moves file position to next line. 4 number Reads number of bytes specified in the function. Other common I/O methods includes, io.tmpfile() − Returns a temporary file for reading and writing that will be removed once the program quits. io.type(file) − Returns whether file, closed file or nil based on the input file. io.flush() − Clears the default output buffer. io.lines(optional file name) − Provides a generic for loop iterator that loops through the file and closes the file in the end, in case the file name is provided or the default file is used and not closed in the end of the loop. Explicit File Descriptors We often use explicit file descriptor which allows us to manipulate multiple files at a time. These functions are quite similar to implicit file descriptors. Here, we use file:function_name instead of io.function_name. The following example of the file version of the same implicit file descriptors example is shown below. — Opens a file in read mode file = io.open(“test.lua”, “r”) — prints the first line of the file print(file:read()) — closes the opened file file:close() — Opens a file in append mode file = io.open(“test.lua”, “a”) — appends a word test to the last line of the file file:write(“–test”) — closes the open file file:close() When you run the program, you will get a similar output as the implicit descriptors example. — Sample test.lua All the modes of file open and params for read for external descriptors is same as implicit file descriptors. Other common file methods includes, file:seek(optional whence, optional offset) − Whence parameter is “set”, “cur” or “end”. Sets the new file pointer with the updated file position from the beginning of the file. The offsets are zero-based in this function. The offset is measured from the beginning of the file if the first argument is “set”; from the current position in the file if it”s “cur”; or from the end of the file if it”s “end”. The default argument values are “cur” and 0, so the current file position can be obtained by calling this function without arguments. file:flush() − Clears the default output buffer. io.lines(optional file name) − Provides a generic for loop iterator that loops through the file and closes the file in the end, in case the file name is provided or the default file is used and not closed in the end of the loop. An example to use the seek method is shown below. It offsets the cursor from the 25 positions prior to the end of file. The read function prints remainder of the file from seek position. — Opens a file in read file = io.open(“test.lua”, “r”) file:seek(“end”,-25) print(file:read(“*a”)) — closes the opened file file:close() You will get some output similar to the following. sample2 test.lua –test You can play around all the different modes and parameters to know the full ability of the Lua file operations. Print Page Previous Next Advertisements ”;

Lua – Garbage Collection

Lua – Garbage Collection ”; Previous Next Lua uses automatic memory management that uses garbage collection based on certain algorithms that is in-built in Lua. As a result of automatic memory management, as a developer − No need to worry about allocating memory for objects. No need to free them when no longer needed except for setting it to nil. Lua uses a garbage collector that runs from time to time to collect dead objects when they are no longer accessible from the Lua program. All objects including tables, userdata, functions, thread, string and so on are subject to automatic memory management. Lua uses incremental mark and sweep collector that uses two numbers to control its garbage collection cycles namely garbage collector pause and garbage collector step multiplier. These values are in percentage and value of 100 is often equal to 1 internally. Garbage Collector Pause Garbage collector pause is used for controlling how long the garbage collector needs to wait, before; it is called again by the Lua”s automatic memory management. Values less than 100 would mean that Lua will not wait for the next cycle. Similarly, higher values of this value would result in the garbage collector being slow and less aggressive in nature. A value of 200, means that the collector waits for the total memory in use to double before starting a new cycle. Hence, depending on the nature and speed of application, there may be a requirement to alter this value to get best performance in Lua applications. Garbage Collector Step Multiplier This step multiplier controls the relative speed of garbage collector to that of memory allocation in Lua program. Larger step values will lead to garbage collector to be more aggressive and it also increases the step size of each incremental step of garbage collection. Values less than 100 could often lead to avoid the garbage collector not to complete its cycle and its not generally preferred. The default value is 200, which means the garbage collector runs twice as the speed of memory allocation. Garbage Collector Functions As developers, we do have some control over the automatic memory management in Lua. For this, we have the following methods. collectgarbage(“collect”) − Runs one complete cycle of garbage collection. collectgarbage(“count”) − Returns the amount of memory currently used by the program in Kilobytes. collectgarbage(“restart”) − If the garbage collector has been stopped, it restarts it. collectgarbage(“setpause”) − Sets the value given as second parameter divided by 100 to the garbage collector pause variable. Its uses are as discussed a little above. collectgarbage(“setstepmul”) − Sets the value given as second parameter divided by 100 to the garbage step multiplier variable. Its uses are as discussed a little above. collectgarbage(“step”) − Runs one step of garbage collection. The larger the second argument is, the larger this step will be. The collectgarbage will return true if the triggered step was the last step of a garbage-collection cycle. collectgarbage(“stop”) − Stops the garbage collector if its running. A simple example using the garbage collector example is shown below. Live Demo mytable = {“apple”, “orange”, “banana”} print(collectgarbage(“count”)) mytable = nil print(collectgarbage(“count”)) print(collectgarbage(“collect”)) print(collectgarbage(“count”)) When we run the above program, we will get the following output. Please note that this result will vary due to the difference in type of operating system and also the automatic memory management feature of Lua. 23.1455078125 149 23.2880859375 295 0 22.37109375 380 You can see in the above program, once garbage collection is done, it reduced the memory used. But, it”s not mandatory to call this. Even if we don”t call them, it will be executed automatically at a later stage by Lua interpreter after the predefined period. Obviously, we can change the behavior of the garbage collector using these functions if required. These functions provide a bit of additional capability for the developer to handle complex situations. Depending on the type of memory need for the program, you may or may not use this feature. But it is very useful to know the memory usage in the applications and check it during the programming itself to avoid undesired results after deployment. Print Page Previous Next Advertisements ”;

Lua – Operators

Lua – Operators ”; Previous Next An operator is a symbol that tells the interpreter to perform specific mathematical or logical manipulations. Lua language is rich in built-in operators and provides the following type of operators − Arithmetic Operators Relational Operators Logical Operators Misc Operators This tutorial will explain the arithmetic, relational, logical, and other miscellaneous operators one by one. Arithmetic Operators Following table shows all the arithmetic operators supported by Lua language. Assume variable A holds 10 and variable B holds 20 then − Show Examples Operator Description Example + Adds two operands A + B will give 30 – Subtracts second operand from the first A – B will give -10 * Multiply both operands A * B will give 200 / Divide numerator by de-numerator B / A will give 2 % Modulus Operator and remainder of after an integer division B % A will give 0 ^ Exponent Operator takes the exponents A^2 will give 100 – Unary – operator acts as negation -A will give -10 Relational Operators Following table shows all the relational operators supported by Lua language. Assume variable A holds 10 and variable B holds 20 then − Show Examples Operator Description Example == Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. ~= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (A ~= B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true. Logical Operators Following table shows all the logical operators supported by Lua language. Assume variable A holds true and variable B holds false then − Show Examples Operator Description Example and Called Logical AND operator. If both the operands are non zero then condition becomes true. (A and B) is false. or Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. (A or B) is true. not Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A and B) is true. Misc Operators Miscellaneous operators supported by Lua Language include concatenation and length. Show Examples Operator Description Example .. Concatenates two strings. a..b where a is “Hello ” and b is “World”, will return “Hello World”. # An unary operator that return the length of the a string or a table. #”Hello” will return 5 Operators Precedence in Lua Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator − For example, x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than &plus; so it first get multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. Show Examples Category Operator Associativity Unary not # – Right to left Concatenation .. Right to left Multiplicative * / % Left to right Additive + – Left to right Relational < > <= >= == ~=  Left to right Equality == ~= Left to right Logical AND and Left to right Logical OR or Left to right Print Page Previous Next Advertisements ”;

Lua – Coroutines

Lua – Coroutines ”; Previous Next Introduction Coroutines are collaborative in nature, which allows two or more methods to execute in a controlled manner. With coroutines, at any given time, only one coroutine runs and this running coroutine only suspends its execution when it explicitly requests to be suspended. The above definition may look vague. Let us assume we have two methods, one the main program method and a coroutine. When we call a coroutine using resume function, its starts executing and when we call yield function, it suspends executing. Again the same coroutine can continue executing with another resume function call from where it was suspended. This process can continue till the end of execution of the coroutine. Functions Available in Coroutines The following table lists all the available functions for coroutines in Lua and their corresponding use. Sr.No. Method & Purpose 1 coroutine.create (f) Creates a new coroutine with a function f and returns an object of type “thread”. 2 coroutine.resume (co [, val1, …]) Resumes the coroutine co and passes the parameters if any. It returns the status of operation and optional other return values. 3 coroutine.running () Returns the running coroutine or nil if called in the main thread. 4 coroutine.status (co) Returns one of the values from running, normal, suspended or dead based on the state of the coroutine. 5 coroutine.wrap (f) Like coroutine.create, the coroutine.wrap function also creates a coroutine, but instead of returning the coroutine itself, it returns a function that, when called, resumes the coroutine. 6 coroutine.yield (…) Suspends the running coroutine. The parameter passed to this method acts as additional return values to the resume function. Example Let”s look at an example to understand the concept of coroutines. Live Demo co = coroutine.create(function (value1,value2) local tempvar3 = 10 print(“coroutine section 1”, value1, value2, tempvar3) local tempvar1 = coroutine.yield(value1+1,value2+1) tempvar3 = tempvar3 + value1 print(“coroutine section 2”,tempvar1 ,tempvar2, tempvar3) local tempvar1, tempvar2= coroutine.yield(value1+value2, value1-value2) tempvar3 = tempvar3 + value1 print(“coroutine section 3”,tempvar1,tempvar2, tempvar3) return value2, “end” end) print(“main”, coroutine.resume(co, 3, 2)) print(“main”, coroutine.resume(co, 12,14)) print(“main”, coroutine.resume(co, 5, 6)) print(“main”, coroutine.resume(co, 10, 20)) When we run the above program, we will get the following output. coroutine section 1 3 2 10 main true 4 3 coroutine section 2 12 nil 13 main true 5 1 coroutine section 3 5 6 16 main true 2 end main false cannot resume dead coroutine What Does the Above Example Do? As mentioned before, we use the resume function to start the operation and yield function to stop the operation. Also, you can see that there are multiple return values received by resume function of coroutine. First, we create a coroutine and assign it to a variable name co and the coroutine takes in two variables as its parameters. When we call the first resume function, the values 3 and 2 are retained in the temporary variables value1 and value2 till the end of the coroutine. To make you understand this, we have used a tempvar3, which is 10 initially and it gets updated to 13 and 16 by the subsequent calls of the coroutines since value1 is retained as 3 throughout the execution of the coroutine. The first coroutine.yield returns two values 4 and 3 to the resume function, which we get by updating the input params 3 and 2 in the yield statement. It also receives the true/false status of coroutine execution. Another thing about coroutines is how the next params of resume call is taken care of, in the above example; you can see that the variable the coroutine.yield receives the next call params which provides a powerful way of doing new operation with the retentionship of existing param values. Finally, once all the statements in the coroutines are executed, the subsequent calls will return in false and “cannot resume dead coroutine” statement as response. Another Coroutine Example Let us look at a simple coroutine that returns a number from 1 to 5 with the help of yield function and resume function. It creates coroutine if not available or else resumes the existing coroutine. Live Demo function getNumber() local function getNumberHelper() co = coroutine.create(function () coroutine.yield(1) coroutine.yield(2) coroutine.yield(3) coroutine.yield(4) coroutine.yield(5) end) return co end if(numberHelper) then status, number = coroutine.resume(numberHelper); if coroutine.status(numberHelper) == “dead” then numberHelper = getNumberHelper() status, number = coroutine.resume(numberHelper); end return number else numberHelper = getNumberHelper() status, number = coroutine.resume(numberHelper); return number end end for index = 1, 10 do print(index, getNumber()) end When we run the above program, we will get the following output. 1 1 2 2 3 3 4 4 5 5 6 1 7 2 8 3 9 4 10 5 There is often a comparison of coroutines with the threads of multiprogramming languages, but we need to understand that coroutines have similar features of thread but they execute only one at a time and never execute concurrently. We control the program execution sequence to meet the needs with the provision of retaining certain information temporarily. Using global variables with coroutines provides even more flexibility to coroutines. Print Page Previous Next Advertisements ”;

Lua – Useful Resources

Lua – Useful Resources ”; Previous Next The following resources contain additional information on Lua. Please use them to get more in-depth knowledge on this topic. Cybersecurity – Da 0 ad Ethical Hacker 133 Lectures 14 hours Giuseppe Compare More Detail Ethical Hacking – Red Team Operations Initial Access to Ransomware Deployment 92 Lectures 14.5 hours AJAY R, Pooja Somu More Detail Noob to Pro in Cheat Engine Speed Course 18 Lectures 34 mins Mateo Kladaric More Detail Print Page Previous Next Advertisements ”;

Lua – Math Library

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 ”;

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 – 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 – 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 ”;