Manual

lua - getting started

Getting Started

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))

Chunks and Blocks

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.

Comments

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.

Standard Libraries

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.

Reblog this post [with Zemanta]

Marcadores: , , , , , ,



# 2/03/2009 11:19:00 AM, Comentários, Links para esta postagem,

lua - variables and expressions

Variables

There are 2 kinds of variables in Lua, global variables, and local variables.
A variable should be explicitly declared local, otherwise it is global. The local variables are lexically scoped and are accessible by the functions defined inside their scope. On the other hand, the global variable is available for use till the end of the program from the point where they are created.
The visibility rules for local and global variables can be easily understood from the example below:
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 

Notice that we assign the value of x in the previous block to the x in the next block. This is possible because the local variables can be freely accessed by the functions defined inside their scope. The local variable used by the inner function is called an upvalue or external local variable, inside the inner function.

Expressions

Expressions yield values. It includes the numeric and string constants (literals), variables, binary & unary operations, function definitions & calls, and table constructors.
Reblog this post [with Zemanta]

Marcadores: , , , , , , , , , ,



# 2/03/2009 11:16:00 AM, Comentários, Links para esta postagem,

lua - arithmetic operators

Arithmetic Operators

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

Relational Operators

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.

Logical Operators

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

Concatenation

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!

Operator Precedence and Associativity

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: , , , , , ,



# 2/03/2009 11:14:00 AM, Comentários, Links para esta postagem,

lua - statements and assignments

Statements

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

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: , , , , , ,



# 2/03/2009 11:13:00 AM, Comentários, Links para esta postagem,

lua - control structures

Control Structures

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.

Condition - if then else

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

Loops - while, repeat, for

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:

for in do end

Where could be a list of variables (with the same scoping rules of the 'i' control loop variable mentioned above). The exp results in an iterator function, a state and an initial value for the first iterator variable.

-- 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.

break and return

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: , , , ,



# 2/03/2009 11:11:00 AM, Comentários, Links para esta postagem,

lua - file io

Basic Input and Output

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.

Implicit Descriptors

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

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: , , , ,



# 2/03/2009 11:07:00 AM, Comentários, Links para esta postagem,