Marcadores: Celular, Computador, Hardware, IBM, Laptop, Mobile, Portable, Privacidade, Resenha, Roubo, Substantivo, Tutorial, Windows
Description: Lua is a powerful, light-weight programming language designed for extending applications. Coupled with it being relatively fast and having a very lenient license, it has gained a following among game developers for providing a viable scripting interface. It has been used in games such as World of Warcraft and Far Cry, and in applications such as Adobe Photoshop Lightroom and Snort.
Lua is a powerful, light-weight programming language designed for extending applications. Lua is also frequently used as a general-purpose, stand-alone language. It is dynamically typed, interpreted from opcodes, great facility to handle strings and other kinds of data with dynamic size, and has automatic memory management with garbage collection, making it ideal for configuration, scripting, and rapid prototyping.
Lua is easily extended not only with software written in Lua itself, but also with software written in other languages, such as C and C++. Lua is also a glue language. Lua supports a component-based approach to software development, where we create an application by gluing together existing high-level components, written in a compiled, statically typed language, such as C or C++; Lua is the glue that we use to compose and connect those components. However, unlike other glue technologies, Lua is a full-fledged language as well. Therefore, we can use Lua not only to glue components, but also to adapt and reshape them, or even to create whole new components.
Lua is not the only scripting language around. There are other languages that you can use for more or less the same purposes, such as Perl, Tcl, Ruby, Forth, and Python. The following features set Lua apart from these languages; although other languages share some of these features with Lua, no other language offers a similar profile:
For detailed information on Lua, please refer to the book Programming in Lua by Roberto Ierusalimschy, and Lua’s official site www.lua.org.
Let's start with the traditional program to print "Hello, world" in Lua:
print("Hello, world")
To run the program, call the Lua interpreter (usually named lua) with the file name that contains the program. For example, if the above program resides in hello.lua, you can run it with:
prompt> lua hello.lua
or you can type the statements directly in the Lua interpreter by invoking the lua without any argument.
Now, let us go further to learn the elements of Lua language by writing a simple program to compute the square of a given number:
-- File mySqr.lua
function mySqr(x) -- Define a Function
return x*x; -- ';' is optional
end
print("Square Calculator")
--[[
Read a number from the user and
print the square value of that number
]]
print("Enter a number :")
n = io.read("*number")
print(mySqr(n))
A chunk is simply a sequence of statements that are executed sequentially. It is the unit of execution in Lua. It could be as simple as a singe statement, as in the "Hello, World" example or a group of statements, optionally separated by a semicolon as in mySqr.lua. A chunk may be stored in a file or in a string in the host program.
A block is a list of statements useful in controlling the scope of the variables. It can be a body of a control structure, body of a function or a chunk.
Anything that follows the double hyphen, --, is interpreted as a comment in Lua and runs till the end of the line. Line 1 in mySqr.lua is a short/single line comment.
If the double hyphen -- is immediately followed by [[, then it is a long comment that may span multiple lines till the matching ]]. Lines 6 through 9 in mySqr.lua represent a long comment. Long comments may contain nested [[ ... ]] pairs.
Lua comes with standard libraries that contain useful functions, as io.read in the above example. These libraries include functions for string manipulation, input & output, mathematical calculations, table manipulation, operating system and debug facilities in addition to the core functions. Please refer to the Lua Reference manual at http://www.lua.org/manual/ for the list of library functions available.
Marcadores: calculator, Computador, English, execution, Lua, manual, mod_lua
and | break | do | else | elseif | |
end | false | for | function | if | |
in | local | nil | not | or | |
repeat | return | then | true | until | while |
nil | Represents the absence of a useful value. When a variable is not initialized, it is automatically set to nil in Lua. A value of nil makes a condition false. |
boolean | Represents the types of true and false values. A value of false makes a condition false. |
number | Represents the real, double precision floating point, numbers. |
string | Represents an array of characters. Lua is 8 bit clean and strings may contain any 8-bit character. Strings can be delimited by double or single quotes. |
function | Functions are first class values in Lua. That means, functions can be stored in a variable, passed as argument to other functions and returned from a function. |
userdata | Represents the block of raw memory. This type is provided to allow arbitrary C data to be stored in the Lua variables. |
thread | Represents the independent threads of execution, used to implement the coroutines. |
table | Represents the associative arrays that can be indexed with any value, except nil. That is, you can index a table with a number or a string or any value except nil. |
print(type(a)) -- nil , as a is not assigned any value yet print(type(nil)) -- nil a=true print(type(a)) -- boolean a=10 print(type(a)) -- number a="hello" print(type(a)) -- string print(type(print)) -– function
Marcadores: boolean, break, elseif, function, Local, Lua, nil, number, repeat, return, string, table, thread, true, types, until, userdata, values, while
x=5 -- Global Variable do -- Start of a block 1 local x=x -- Local Variable print (x) -- Prints 5 x=x+2 -- Modifies local x print (x) -- Prints 7 do -- Start of block 2 local x=x+4 -- Yet another local x :) print (x) -- prints 11 end -- End of block 2 print (x) -- Prints 7 end -- End of block 1 print (x) -- Prints 5, global variable
Marcadores: Computador, English, expressions, Language, Lua, manual, mod_lua, Scope, Scripting, Variable, variables
Lua provides the usual operators: the binary '+' (addition), '-' (subtraction), '*' (multiplication), '/' (division), and '^' exponentiation; and unary '-' (negation).
The operand can be numbers or strings that can be converted to numbers. All the operators except exponentiation have the usual meaning. The exponentiation operator calls the math.pow function in the standard mathematical library.
-- Arithmetic Operators
a=5
b=3
print(a+b) -- 8
print(a-b) -- 2
print(a*b) -- 15
print(a/b) -- 1.667
print(a^b) -- 125 calls the math.pow function
print(-a) -- -5
The relational operators allow two values to be compared and always result in true or false values. Lua provides the following operators: '==' (equality), '~=' (inequality), '<' (less than), '>' (greater than), '<=' (less than or equal to) and '>=' (greater than or equal to).
The == and ~= operators first compares the types of the operands. It the types are different, the result of the expression is false. If the types are same, then the values of the operands are compared for numbers and strings in the usual way. However, the automatic conversion of string and number values do not apply to equality comparison, as 0 and "0" are two different types. Objects (tables, userdata, threads, and functions) are compared by reference. Two objects are equal only if they are the same object.
-- Equality Operators
a=7; b=5; c="a string"
print(a==c) -- false, as a holds a number and c a string
print(a~=c) -- false here too for the same reason
print(a==b) -- false as 7 is not equal to 5
print(a~=5) -- true as 7 is not equal to 5
The <, >, <=, >= operators work in the usual way.
The logical operators in Lua are and, or and not. All logical operators consider nil and false as false, and anything else as true (in particular, the number 0 and empty string are also true).
The operator not always returns false or true.
The and operator returns its first argument if this value is false or nil, otherwise it returns its second argument. The or operator returns its first argument if this value is true, otherwise it returns its second argument. Both the and and or operators use short-cut evaluation, that is, the second argument is evaluated only if necessary. For example, consider the code below:
a=5;b=3
print(nil and (c=a+b)) -- nil, as the first argument is nil
print(c) -- nil, as the second argument is
-- evaluated by and operator
The expression c=a+b is not evaluated as the first argument is nil. Few more expressions here would help you understand the logical operators:
-- Logical Operators
print(0 and false) -- false, as 0 yields true
print(false and 5) -- false
print(4 and nil) -- 4
print(4 or 7) -- 7
print(nil or 3) -- 3
print(false or nil) -- nil
print(false and nil) -- false
print(not false) -- true
print(not nil) -- true
print(not 56) -- false
Lua provides '..' as the concatenation operator to concatenate two strings. If the operands are numbers, they are automatically converted to strings.
-- Concatenation
print("Learning " .. "Lua!") -- Learning Lua!
Precedence controls the order of evaluation of operators in an expression and associativity controls the order of evaluation of operators with same precedence level. The precedence of operators is given below, from lower to higher priority: or
and
< > <= >= ~= ==
..
+ -
* /
not – (unary)
^
The concatenation (..) and exponentiation (^) operators are right associative and rest of the operators are left associative.
Marcadores: arithmetic, Computador, English, Lua, manual, mod_lua, operadores
Like many programming languages, Lua supports a conventional set of statements for assignment, control structures, function calls, variable declarations. In addition, Lua supports multiple assignments, table constructors and local declarations.
Assignment statement allows you to give a value to a variable. Most programming languages allow single assignment as below:
a = 7
But, Lua allows multiple assignments, that is, a list of variables can be assigned with a list values in one statement. Consider the example here:
a, b, c = 1, 7, "hello"
Here a is assigned 1, b gets 7 and c gets "hello". The lists on either side of = are separated by comma. Lua evaluates all the expressions before performing assignment. For example, in
i = 3
i, a[i] = i+1, 20
20 is assigned to a[3], without affecting a[4]. This is because, the i in a[i] is evaluated before it is assigned to 4. Similarly, the statement
x, y = y, x
swaps the values of x and y.
Now, what happens if the number of values in the list is not equal to the number of variables? In that case, Lua adjusts the number of values to the number of variables. When the number of values is less than the list of variables, the list of values is extended with as many nil's as needed. Similarly, when the length of the list of values is more than the list of variables, the excess values are discarded or thrown away.
-- Multiple Assignments
a, b, c = 1, true, 5
print(a,b,c) -- 1 true 5
a, b, c = 10
print(a,b,c) -- 10 nil nil
a, b, c = 1, 2, 3, 4 -- 4 is discarded
print(a,b,c) -- 1 2 3
In Lua, a function call can return multiple values. So when a function call is placed in the list of values, the return values are adjusted depending on the position of the function call in the list.
Marcadores: assignments, Computador, English, Lua, manual, mod_lua, statements
The control structure statements allow you to control/alter the execution of the statements based on some condition. Lua provides if for conditional and while, repeat and for for iteration/looping. The conditional expression in a control structure may return any value. nil and false makes the condition fail, any other value results in true satisfying the condition.
The if statement tests the condition and executes the then block on true or else block on false. The else block is optional. In case of nested if-else statements, elseif can be used to nest them.
-- if then else
a, b = 2, 6
if a < style="color: rgb(6, 0, 255);">then
print("a less than b")
elseif a > b then
print("a greater than b")
else
print("a equal to b")
end
The while statement allows the execution of a block of code until the condition is true.
-- while loop
i = 1
while i <= 10 do
print(i)
i = i + 1
end
The repeat statement also allows the execution of a block of code until the condition is true. But, the condition is tested after the execution of the block, so the block is always executed at least once.
-- repeat loop
i = 1
repeat
print(i)
i = i + 1
until i <= 10
The for statement has two forms: one numeric and one generic.
The numeric form has the following syntax:
for var = exp1, exp2, exp3 do block end
The loop will execute the statements in the block for each value of var from exp1 to exp2, using exp3 as the step to increment var. exp3 is optional and when absent, Lua assumes one as the step value.
-- Numeric for loop printing odd nums from 1 to 10
for i = 1, 10, 2
do
print(i)
end
-- i is not defined here, so its value is nil
In the above example, the loop control variable (i), is initialized to 1 and the loop continues till its value is less than 10. At the end of each iteration, i is incremented by 2.
One point to note here is that, the loop control variable i is a local variable and is not accessible or visible outside the for loop so there is no way to access its value outside of the loop. The value of such variables might be stored in a separate variable before exiting the for loop, if necessary.
The generic for loop allows you to traverse all values returned by an iterator function. For each iteration, it calls its iteration function to produce a new value, stopping when the new value is nil. Its general syntax is:
forin do end
Where
-- Numeric Iterator
for i in io.lines("mySqr.lua")
do
print(i)
end
The io.lines is a standard library function that opens the file given as its argument and returns an iterator function that reads one line at a time from the file. The above chunk prints the mySqrt.lua program discussed earlier in this tutorial.
The break and return statements allow you to jump out from an inner block. While a return statement allows you to return results from a function, the break statement allows you to terminate a loop. break breaks the inner loop that contain it.
-- break example
i = 0
while i < 10 do
if i == 5 then break end
i = i + 1
end
For syntactic reasons, break and return can appear only as the last statement of a block. If you need to return or break in the middle, you need to enclose the break and return statement in an explicit block.
-- return example
function fun()
print("Inside fun")
print("Enter a number:")
local num = io.read()
if (tonumber(num) == 10) then
print("You have entered 10");
do return 10 end
print("This statement is not executed")
end
return num
end
Marcadores: Computador, English, Lua, manual, mod_lua
Lua provides functions for basic input and output through its standard I/O library. The I/O library provides two different styles for file manipulation with implicit and explicit file descriptors. A file descriptor is a handle that allows you to manipulate the file which it corresponds to.
Lua always assume a default set of file descriptors for I/O: the process's standard input for input, and the process's standard output for output. When you don't specify any file descriptors, the file operations will be performed with these standard default descriptors. As you might have seen in the earlier examples, the call to io.read() reads the data from the process's standard input, typically the keyboard.
You can change the default descriptor for I/O with the io.input() and io.output() functions. These functions take the file name as the argument and from this point any input/output will be to these respective files, until another call is made to io.input() to change the input file or io.output() to change the output file.
-- Implicit Descriptor Example
io.write("Enter a number:") -- Writes to process's std output
a = io.read() -- Reads from process's std input
print("Value of a is", a) -- Always writes to std output
io.input("mySqrt.lua") -- Change the input to mySqrt.lua
io.output("mySqrtDup.lua") -- Change the output to new file
local lineCount = 0
while true do
local line = io.read() -- Reads a line from mySqrt.lua
if (line == nil) then break end -- Jump out of loop on EOF
io.write(line) -- Write to the new file
lineCount = lineCount + 1
end
print("Number of lines copied =", lineCount)
The io.read() function reads strings from the current input file. Its argument controls what is being read:
"*all" | reads the whole file |
"*line" | reads the next line |
"*number" | reads a number |
num | reads a string with up to num characters |
The call io.read("*all") returns the whole input file from its current position. It returns an empty string if the file is empty or the current position is EOF (end of file).
The call io.read("*line") returns the next line from the file, without the newline character. It returns a nil on EOF. Lua defaults to io.read("*line") when no argument is passed to io.read(). The iterator io.lines() might also be used to read a file line by line.
The io.read("*number") returns a number from the current input file. This is the only case where read returns a number instead of a string. It returns a nil, if it cannot find a number at the current position.
Explicit descriptors give you the full control on I/O. The central concept in this model is the file handle which represent an open file with a current position. To open a file, you use the io.open() function, that takes the filename and open mode as its argument. The different modes are 'r' for read, 'w' for write and 'a' for append (appending 'b' to the modes, causes the file to be opened for read, write and append in binary mode).
The read and write operations are performed subsequently with the read and write functions, scoped by the file handle using the colon syntax. For example, to open a file and read all its content,
-- Explicit Descriptor/handle
f = io.open(filename, "r")
if (f ~= nil) then
local t = f:read("*all")
f:close()
else
print("Cannot not open", filename)
end
With explicit file descriptor method, you can have multiple input files and output files open simultaneously.
Marcadores: Computador, English, Lua, manual, mod_lua