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





Links para esta postagem:

Criar um link



<< Início

Arquivos

Assinar Postagens [Atom]




count

count