Variable

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,