Lua syntax

来源:互联网 发布:淘宝闲置物品怎么下架 编辑:程序博客网 时间:2024/05/19 02:18

Chapter 1: Getting Started

1.1 Chunks

Each piece of code that Lua executes, such as a file or a single line in interactive mode, is called a chunk. A chunk is simply a sequence of commands (or statements).

Another way to run chunks is with the dofile function, which immediately executes a file.


1.2 Some Lexical Conventions

Identifiers in Lua can be any string of letters, digits, and underscores, not beginning with a digit;

A comment starts anywhere with a double hyphen (--) and runs until the end of the line. Lua also offers block comments, which start with --[[ and run until the next ]].


1.3 Global Variables

Global variables do not need declarations. if you need to delete a global variable, just assign nil to it.


1.4 The Stand-Alone Interpreter

A script can retrieve its arguments in the global variable arg. 

% lua script a b c

arg[0] = "script"
arg[1] = "a"
arg[2] = "b"


Chapter 2: Types and Values

print(type("Hello world")) --> string

2.1 Nil

Nil is a type with a single value, nil.


2.2 Booleans

The boolean type has two values, false and true.

both false and nil as false and anything else as true.


2.3 Numbers

The number type represents real (double-precision floating-point) numbers. it uses another type for numbers, such as longs or single-precision floats. See file luaconf.h in the distribution for detailed instructions.

4   0.4   4.57e-3   0.3e12   5e+20


2.4 String

Lua is eight-bit clean and its strings may contain characters with any numeric code, including embedded zeros. 

You cannot change a character inside a string, as you may in C; instead, you create a new string with the desired modifications.

We can delimit literal strings also by matching double square brackets, as we do with long comments.

page = [[
<html>
<head>
<title>An HTML Page</title>
</head>
<body>
<a href="http://www.lua.org">Lua</a>
</body>
</html>
]]
write(page)

For instance, if you start a long comment with --[=[, it extends until the next ]=].

The .. is the string concatenation operator in Lua.

If you need to convert a string to a number explicitly, you can use the function tonumber. To convert a number to a string, you can call the function tostring. 

you can get the length of a string using the prex operator `#'.


2.5 Table

The table type implements associative arrays. An associative array is an array that can be indexed not only with numbers, but also with strings or any other value of the language, except nil.

a = {} -- create a table and store its reference in 'a'
k = "x"
a[k] = 10 -- new entry, with key="x" and value=10
a[20] = "great" -- new entry, with key=20 and value="great"
print(a["x"]) --> 10
k = 20
print(a[k]) --> "great"
a["x"] = a["x"] + 1 -- increments entry "x"
print(a["x"]) --> 11

a.x = 10 -- same as a["x"] = 10
print(a.x) -- same as print(a["x"])

it is customary in Lua to start arrays with 1 (and not with 0, as in C).


2.6 Functions

This means that functions can be stored in variables, passed as arguments to other functions, and returned as results.


2.7 Userdata and Threads

The userdata type allows arbitrary C data to be stored in Lua variables.


Chapter 3: Expressions

3.1 Arithmetic Operators

Lua supports the usual arithmetic operators: the binary `+' (addition), `-' (subtraction), `*' (multiplication), `/' (division), `^' (exponentiation), `%' (modulo), and the unary `-' (negation).


3.2 Relational Operators

Lua provides the following relational operators:
< > <= >= == ~=


3.3 Logical Operators

The logical operators are and, or, and not.


3.4 Concatenation

If any of `..`'s operands is a number, Lua converts this number to a string.


3.5 Precedence

All binary operators are left associative, except for `^' (exponentiation) and `..'(concatenation), which are right associative.


3.6 Table Constructors

Constructors are expressions that create and initialize tables.

The simplest constructor is the empty constructor, {}, which creates an empty table; we have seen it before. Constructors also initialize arrays (called also sequences or lists). For instance, the statement

days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}

w = {x=0, y=0, label="console"}
x = {math.sin(0), math.sin(1), math.sin(2)}
w[1] = "another field" -- add key 1 to table 'w'
x.f = w -- add key "f" to table 'x'
print(w["x"]) --> 0
print(w[1]) --> another field
print(x.f[1]) --> another field
w.x = nil -- remove field "x"

polyline = {color="blue", thickness=2, npoints=4,
{x=0, y=0},
{x=-10, y=0},
{x=-10, y=1},
{x=0, y=1}
}

print(polyline[2].x) --> -10
print(polyline[4].y) --> 1


Chapter 4: Statements

4.1 Assignment

a, b = 10, 2*x


4.2 Local Variables and Blocks

Unlike global variables, local variables have their scope limited to the block where they are declared. A block is the body of a control structure, the body of a function, or a chunk (the file or string where the variable is declared).

These do blocks are useful also when you need finer control over the scope of some local variables.

A common idiom in Lua is
local foo = foo

This idiom is useful when the chunk needs to preserve the original value of foo even if later some other function changes the value of the global foo.


4.3 Control Structures

if op == "+" then
r = a + b
elseif op == "-" then
r = a - b
elseif op == "*" then
r = a*b
elseif op == "/" then
r = a/b
else
error("invalid operation")
end

local i = 1
while a[i] do
print(a[i])
i = i + 1
end

local sqr = x/2
repeat
sqr = (sqr + x/sqr)/2
local error = math.abs(sqr^2 - x)
until error < x/10000 -- 'error' still visible here

for var=exp1,exp2,exp3 do
<something>
end

for i,v in ipairs(a) do print(v) end


4.4 break and return

a break or return can appear only as the last statement of a block.

function foo ()
return --<< SYNTAX ERROR
-- 'return' is the last statement in the next block
do return end -- OK
<other statements>
end