Lua – Variables

Lua – Variables ”; Previous Next A variable is nothing but a name given to a storage area that our programs can manipulate. It can hold different types of values including functions and tables. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Lua is case-sensitive. There are eight basic types of values in Lua − In Lua, though we don”t have variable data types, we have three types based on the scope of the variable. Global variables − All variables are considered global unless explicitly declared as a local. Local variables − When the type is specified as local for a variable then its scope is limited with the functions inside their scope. Table fields − This is a special type of variable that can hold anything except nil including functions. Variable Definition in Lua A variable definition means to tell the interpreter where and how much to create the storage for the variable. A variable definition have an optional type and contains a list of one or more variables of that type as follows − type variable_list; Here, type is optionally local or type specified making it global, and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here − local i, j local i local a,c The line local i, j both declares and defines the variables i and j; which instructs the interpreter to create variables named i, j and limits the scope to be local. Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows − type variable_list = value_list; Some examples are − local d , f = 5 ,10 –declaration of d and f as local variables. d , f = 5, 10; –declaration of d and f as global variables. d, f = 10 –[[declaration of d and f as global variables. Here value of f is nil –]] For definition without an initializer: variables with static storage duration are implicitly initialized with nil. Variable Declaration in Lua As you can see in the above examples, assignments for multiples variables follows a variable_list and value_list format. In the above example local d, f = 5,10 we have d and f in variable_list and 5 and 10 in values list. Value assigning in Lua takes place like first variable in the variable_list with first value in the value_list and so on. Hence, the value of d is 5 and the value of f is 10. Example Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function − Live Demo — Variable definition: local a, b — Initialization a = 10 b = 30 print(“value of a:”, a) print(“value of b:”, b) — Swapping of variables b, a = a, b print(“value of a:”, a) print(“value of b:”, b) f = 70.0/3.0 print(“value of f”, f) When the above code is built and executed, it produces the following result − value of a: 10 value of b: 30 value of a: 30 value of b: 10 value of f 23.333333333333 Lvalues and Rvalues in Lua There are two kinds of expressions in Lua − lvalue − Expressions that refer to a memory location is called “lvalue” expression. An lvalue may appear as either the left-hand or right-hand side of an assignment. rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it, which means an rvalue may appear on the right-hand side, but not on the left-hand side of an assignment. Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and cannot appear on the left-hand side. Following is a valid statement − g = 20 But following is not a valid statement and would generate a build-time error − 10 = 20 In Lua programming language, apart from the above types of assignment, it is possible to have multiple lvalues and rvalues in the same single statement. It is shown below. g,l = 20,30 In the above statement, 20 is assigned to g and 30 is assigned to l. Print Page Previous Next Advertisements ”;

Lua – Basic Syntax

Lua – Basic Syntax ”; Previous Next Let us start creating our first Lua program! First Lua Program Interactive Mode Programming Lua provides a mode called interactive mode. In this mode, you can type in instructions one after the other and get instant results. This can be invoked in the shell by using the lua -i or just the lua command. Once you type in this, press Enter and the interactive mode will be started as shown below. $ lua -i $ Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio quit to end; cd, dir and edit also available You can print something using the following statement − print(“test”) Once you press enter, you will get the following output − test Default Mode Programming Invoking the interpreter with a Lua file name parameter begins execution of the file and continues until the script is finished. When the script is finished, the interpreter is no longer active. Let us write a simple Lua program. All Lua files will have extension .lua. So put the following source code in a test.lua file. Live Demo print(“test”) Assuming, lua environment is setup correctly, let’s run the program using the following code − $ lua test.lua We will get the following output − test Let”s try another way to execute a Lua program. Below is the modified test.lua file − Live Demo #!/usr/local/bin/lua print(“test”) Here, we have assumed that you have Lua interpreter available in your /usr/local/bin directory. The first line is ignored by the interpreter, if it starts with # sign. Now, try to run this program as follows − $ chmod a+rx test.lua $./test.lua We will get the following output. test Let us now see the basic structure of Lua program, so that it will be easy for you to understand the basic building blocks of the Lua programming language. Tokens in Lua A Lua program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Lua statement consists of three tokens − io.write(“Hello world, from “,_VERSION,”!n”) The individual tokens are − io.write ( “Hello world, from “,_VERSION,”!n” ) Comments Comments are like helping text in your Lua program and they are ignored by the interpreter. They start with –[[ and terminates with the characters –]] as shown below − –[[ my first program in Lua –]] Identifiers A Lua identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter ‘A to Z’ or ‘a to z’ or an underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to 9). Lua does not allow punctuation characters such as @, $, and % within identifiers. Lua is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in Lua. Here are some examples of the acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal Keywords The following list shows few of the reserved words in Lua. These reserved words may not be used as constants or variables or any other identifier names. and break do else elseif end false for function if in local nil not or repeat return then true until while Whitespace in Lua A line containing only whitespace, possibly with a comment, is known as a blank line, and a Lua interpreter totally ignores it. Whitespace is the term used in Lua to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as int ends, and the next element begins. Therefore, in the following statement − local age There must be at least one whitespace character (usually a space) between local and age for the interpreter to be able to distinguish them. On the other hand, in the following statement − fruit = apples + oranges –get the total fruit No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose. Print Page Previous Next Advertisements ”;

Lua – Discussion

Discuss Lua ”; Previous Next Lua is an open source language built on top of C programming language. Lua has its value across multiple platforms ranging from large server systems to small mobile applications. This tutorial covers various topics ranging from the basics of Lua to its scope in various applications. Print Page Previous Next Advertisements ”;

Lua – Quick Guide

Lua – Quick Guide ”; Previous Next Lua – Overview Lua is an extensible, lightweight programming language written in C. It started as an in-house project in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes. It was designed from the beginning to be a software that can be integrated with the code written in C and other conventional languages. This integration brings many benefits. It does not try to do what C can already do but aims at offering what C is not good at: a good distance from the hardware, dynamic structures, no redundancies, ease of testing and debugging. For this, Lua has a safe environment, automatic memory management, and good facilities for handling strings and other kinds of data with dynamic size. Features Lua provides a set of unique features that makes it distinct from other languages. These include − Extensible Simple Efficient Portable Free and open Example Code print(“Hello World!”) How Lua is Implemented? Lua consists of two parts – the Lua interpreter part and the functioning software system. The functioning software system is an actual computer application that can interpret programs written in the Lua programming language. The Lua interpreter is written in ANSI C, hence it is highly portable and can run on a vast spectrum of devices from high-end network servers to small devices. Both Lua”s language and its interpreter are mature, small, and fast. It has evolved from other programming languages and top software standards. Being small in size makes it possible for it to run on small devices with low memory. Learning Lua The most important point while learning Lua is to focus on the concepts without getting lost in its technical details. The purpose of learning a programming language is to become a better programmer; that is, to become more effective in designing and implementing new systems and at maintaining old ones. Some Uses of Lua Game Programming Scripting in Standalone Applications Scripting in Web Extensions and add-ons for databases like MySQL Proxy and MySQL WorkBench Security systems like Intrusion Detection System. Lua – Environment Local Environment Setup If you are still willing to set up your environment for Lua programming language, you need the following softwares available on your computer – (a) Text Editor, (b) The Lua Interpreter, and (c) Lua Compiler. Text Editor You need a text editor to type your program. Examples of a few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of the text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on Windows as well as Linux or UNIX. The files you create with your editor are called source files and these files contain the program source code. The source files for Lua programs are typically named with the extension “.lua”. The Lua Interpreter It is just a small program that enables you to type Lua commands and have them executed immediately. It stops the execution of a Lua file in case it encounters an error unlike a compiler that executes fully. The Lua Compiler When we extend Lua to other languages/applications, we need a Software Development Kit with a compiler that is compatible with the Lua Application Program Interface. Installation on Windows There is a separate IDE named “SciTE” developed for the windows environment, which can be downloaded from https://code.google.com/p/luaforwindows/ download section. Run the downloaded executable to install the Lua IDE. Since it’s an IDE, you can both create and build the Lua code using the same. In case, you are interested in installing Lua in command line mode, you need to install MinGW or Cygwin and then compile and install Lua in windows. Installation on Linux To download and build Lua, use the following command − $ wget http://www.lua.org/ftp/lua-5.2.3.tar.gz $ tar zxf lua-5.2.3.tar.gz $ cd lua-5.2.3 $ make linux test In order to install on other platforms like aix, ansi, bsd, generic linux, mingw, posix, solaris by replacing Linux in make Linux, test with the corresponding platform name. We have a helloWorld.lua, in Lua as follows − print(“Hello World!”) Now, we can build and run a Lua file say helloWorld.lua, by switching to the folder containing the file using cd, and then using the following command − $ lua helloWorld We can see the following output. Hello World! Installation on Mac OS X To build/test Lua in the Mac OS X, use the following command − $ curl -R -O http://www.lua.org/ftp/lua-5.2.3.tar.gz $ tar zxf lua-5.2.3.tar.gz $ cd lua-5.2.3 $ make macosx test In certain cases, you may not have installed the Xcode and command line tools. In such cases, you won’t be able to use the make command. Install Xcode from mac app store. Then go to Preferences of Xcode, and then switch to Downloads and install the component named “Command Line Tools”. Once the process is completed, make command will be available to you. It is not mandatory for you to execute the “make macosx test” statement. Even without executing this command, you can still use Lua in Mac OS X. We have a helloWorld.lua, in Lua, as follows − print(“Hello World!”) Now, we can build and run a Lua file say helloWorld.lua by switching to the folder containing the file using cd and then using the following command − $ lua helloWorld We can see the following output − Hello World! Lua IDE As mentioned earlier, for Windows SciTE, Lua IDE is the default IDE provided by the Lua creator team. The alternate IDE available is from ZeroBrane Studio, which is available across multiple platforms like Windows, Mac and Linux. There are also plugins for eclipse that enable the Lua development. Using IDE makes it easier for development with features like code completion and is highly recommended. The IDE also provides interactive mode programming similar to the command line version of Lua. Lua – Basic Syntax Let us start creating our

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 – Operating System Facilities

Lua – Operating System Facilities ”; Previous Next In any application, it is often required for to access Operating System level functions and it is made available with Operating System library. The list of functions available are listed in the following table. Sr.No. Library / Method & Purpose 1 os.clock () Returns an approximation of the amount in seconds of CPU time used by the program. 2 os.date ([format [, time]]) Returns a string or a table containing date and time, formatted according to the given string format. 3 os.difftime (t2, t1) Returns the number of seconds from time t1 to time t2. In POSIX, Windows, and some other systems, this value is exactly t2-t1. 4 os.execute ([command]) This function is equivalent to the ANSI C function system. It passes command to be executed by an operating system shell. Its first result is true if the command terminated successfully, or nil otherwise. 5 os.exit ([code [, close]) Calls the ANSI C function exit to terminate the host program. If code is true, the returned status is EXIT_SUCCESS; if code is false, the returned status is EXIT_FAILURE; if code is a number, the returned status is this number. 6 os.getenv (varname) Returns the value of the process environment variable varname, or nil if the variable is not defined. 7 os.remove (filename) Deletes the file (or empty directory, on POSIX systems) with the given name. If this function fails, it returns nil, plus a string describing the error and the error code. 8 os.rename (oldname, newname) Renames file or directory named oldname to newname. If this function fails, it returns nil, plus a string describing the error and the error code. 9 os.setlocale (locale [, category]) Sets the current locale of the program. locale is a system-dependent string specifying a locale; category is an optional string describing which category to change: “all”, “collate”, “ctype”, “monetary”, “numeric”, or “time”; the default category is “all”. The function returns the name of the new locale, or nil if the request cannot be honored. 10 os.time ([table]) Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour (default is 12), min (default is 0), sec (default is 0), and isdst (default is nil). For a description of these fields, see the os.date function. 11 os.tmpname () Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed. Common OS functions A simple example using common math functions is shown below. Live Demo — Date with format io.write(“The date is “, os.date(“%m/%d/%Y”),”n”) — Date and time io.write(“The date and time is “, os.date(),”n”) — Time io.write(“The OS time is “, os.time(),”n”) — Wait for some time for i=1,1000000 do end — Time since Lua started io.write(“Lua started before “, os.clock(),”n”) When we run the above program, we will get similar output to the following. The date is 01/25/2014 The date and time is 01/25/14 07:38:40 The OS time is 1390615720 Lua started before 0.013 The above examples are just a few of the common examples, we can use OS library based on our need, so try using all the functions to be more familiar. There are functions like remove which helps in removing file, execute that helps us executing OS commands as explained above. Print Page Previous Next Advertisements ”;

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