Lua(0) first
------------------------------------------------------------------
value
a = 1 b = a*2 a = 1; b = a*2; a = 1; b = a*2 a = 1 b = a*2 -- ugly, but valid
-----------------------------------------------------------------
Types and Values
print(type("Hello world")) --> string print(type(10.4*3)) --> number print(type(print)) --> functio print(type(type)) --> functio print(type(true)) --> boolean print(type(nil)) --> nil print(type(type(X))) --> string
print(type(a)) --> nil ('a' is not initialized) a = 10 print(type(a)) --> number a = "a string!!" print(type(a)) --> string a = print -- yes, this is valid! a(type(a)) --> function
Nil; Boolean; number; string
number
print("10" + 1) --> 11 print("10 + 1") --> 10 + 1 print("-5.3e-10"*"2") --> -1.06e-09 print("hello" + 1) -- ERROR (cannot convert "hello")
string
a = "hello" print(#a) --> 5 print(#"good\0bye") --> 8
Misc
(1)
line = io.read() -- read a line n = tonumber(line) -- try to convert it to a number if n == nil then error(line .. " is not a valid number") else print(n*2) end
(2)
print(tostring(10) == "10") --> true print(10 .. "" == "10") --> true
table(差不多相当于对象)
(1)
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
(2)
a = {} a["x"] = 10 b = a -- 'b' refers to the same table as 'a' print(b["x"]) --> 10 b["x"] = 20 print(a["x"]) --> 20 a = nil -- only 'b' still refers to the table b = nil -- no references left to the table
(3)
a = {} -- empty table
-- create 1000 new entries
for i = 1, 1000 do a[i] = i*2 end
print(a[9]) --> 18
a["x"] = 10
print(a["x"]) --> 10
print(a["y"]) --> nil
(4)
a.x = 10 -- same as a["x"] = 10 print(a.x) -- same as print(a["x"]) print(a.y) -- same as print(a["y"])
(5)
a = {} x = "y" a[x] = 10 -- put 10 in field "y" print(a[x]) --> 10 -- value of field "y" print(a.x) --> nil -- value of field "x" (undefined) print(a.y) --> 10 -- value of field "y"
(6)
-- read 10 lines, storing them in a table a = {} for i = 1, 10 do a[i] = io.read() end -- print the lines for i = 1, #a do print(a[i]) end
(7)
i = 10; j = "10"; k = "+10" a = {} a[i] = "one value" a[j] = "another value" a[k] = "yet another value" print(a[i]) --> one value print(a[j]) --> another value print(a[k]) --> yet another value print(a[tonumber(j)]) --> one value print(a[tonumber(k)]) --> one value
------------------------------------------
Function
-----------------------------------------
Userdata and Threads
------------------------------------------
Arithmetic Operators
-->The following rule defines the modulo(模) operator: a % b == a - math.floor(a/b)*b
-->Similarly, x-x%0.01 is x with exactly two decimal digits: x = math.pi print(x - x%0.01) --> 3.14
angle && degree
-->If theangle is given in degrees, you can use the following formula: local tolerance = 10 function isturnback (angle) angle = angle % 360 return (math.abs(angle - 180) < tolerance) end -->This definition works even for negative angles: print(isturnback(-180)) --> true -->If we want to work with radians instead of degrees, we simply change the -->constants in our function: local tolerance = 0.17 function isturnback (angle) angle = angle % (2*math.pi) return (math.abs(angle - math.pi) < tolerance) end -->The operation angle%(2*math.pi) is all we need to normalize any angle to avalue in the interval [0; 2∏).
------------------------------------------------
Operators
-----------
Relational Operators
< > <= >= == ~=
compulate
a = {}; a.x = 1; a.y = 0
b = {}; b.x = 1; b.y = 0
c = a
-->you have a==c but a~=b.
Logical Operators
and, or, and not.
compulate
print(4 and 5) --> 5 print(nil and 13) --> nil print(false and 13) --> false print(4 or 5) --> 4 print(false or 5) --> 5
show
-->A useful Lua idiom is x=x or v, which is equivalent to if not x then x = v end
get max
-->select the maximum of two numbers x and y with a statement like max = (x > y) and x or y
not
-->The not operator always returns a boolean value: print(not nil) --> true print(not false) --> true print(not 0) --> false print(not not 1) --> true print(not not nil) --> false
------------------------------------------------------
Concatenation
----------------
Concatenation
print("Hello " .. "World") --> Hello World print(0 .. 1) --> 01 print(000 .. 01) --> 01 a = "Hello" print(a .. " World") --> Hello World print(a) --> Hello
The Length Operator
print(a[#a]) -- prints the last value of sequence 'a' a[#a] = nil -- removes this last value a[#a + 1] = v -- appends 'v' to the end of the list
length of table
a = {} a[1] = 1 a[2] = nil --> does nothing, as a[2] is already nil a[3] = 1 a[4] = 1 -->It is easy to say that the length of this list is four, and that is has a hole at index 2. However, what can we say about the next similar example? a = {} a[1] = 1 a[10000] = 1
length of table
a = {10, 20, 30, nil, nil}
--> its length is 3, not 5.
-->table is equal to {10,20,30}
------------------------------------------
Precedence(优先级)
逻辑运算符认为false和nil是假(false),其他为真,0也是true.
^ not # - (unary) * / % + - .. < > <= >= ~= == and or
for instance:
a+i < b/2+1 --> (a+i) < ((b/2)+1) 5+x^2*8 --> 5+((x^2)*8) a < y and y <= z --> (a < y) and (y <= z) -x^2 --> -(x^2) x^y^z --> x^(y^z)
----------------------------------------------------
Table Constructors
-->For instance, the statement days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} print(days[4]) --> Wednesday
secord instance:
a = {x=10, y=20}
-->This previous line is equivalent to these commands:
a = {}; a.x=10; a.y=20
third instance:
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"
forth instance:
-->can mix record-style and list-style initializations in the same constructor: polyline = {color="blue", thickness=2, npoints=4, {x=0, y=0}, -- polyline[1] {x=-10, y=0}, -- polyline[2] {x=-10, y=1}, -- polyline[3] {x=0, y=1} -- polyline[4] } print(polyline[2].x) --> -10 print(polyline[4].y) --> 1
fifth instance:
-->explicitly write the index to be initialized as an expression, between square brackets([]): -->This syntax is more cumbersome(累赘), but more flexible(灵活) too opnames = {["+"] = "add", ["-"] = "sub", ["*"] = "mul", ["/"] = "div"} i = 20; s = "-" a = {[i+0] = s, [i+1] = s..s, [i+2] = s..s..s} print(opnames[s]) --> sub print(a[22]) --> --- -->You can always put a comma(,) after the last entry. These trailing(尾) commas are optional, but are always valid: a = {[1]="red", [2]="green", [3]="blue",}
sixth instance:
-->最后,你可以使用分号来代替一个逗号在一个构造函数。 我通常储备分号分隔不同部分在一个构造函数,实例分离部分的记录部分列表: {x=10, y=45; "one", "two", "three"}
--------------------------------------------
Statements(声明)
--------------------------------------
Assignment(赋值)
a = "hello" .. "world" t.n = t.n + 1 a, b = 10, 2*x x, y = y, x -- swap 'x' for 'y' a[i], a[j] = a[j], a[i] -- swap 'a[i]' for 'a[j]' a, b, c = 0, 1 print(a, b, c) --> 0 1 nil a, b = a+1, b+1, b+2 -- value of b+2 is ignored print(a, b) --> 1 2 a, b, c = 0 print(a, b, c) --> 0 nil nil a, b, c = 0, 0, 0 print(a, b, c) --> 0 0 0
Local Variables and Blocks(局部变量)
local variables have their scope limited to the block where they are declared.
first instance:
j = 10 -- global variable local i = 1 -- local variable x = 10 local i = 1 -- local to the chunk while i <= x do local x = i*2 -- local to the while body print(x) --> 2, 4, 6, 8, ... i = i + 1 end
second instance:
These do blocks are useful also when you need finer control over the scope of some local variables: do local a2 = 2*a local d = (b^2 - 4*a*c)^(1/2) x1 = (-b + d)/a2 x2 = (-b - d)/a2 end -- scope of 'a2' and 'd' ends here print(x1, x2)
third instance:
--If a declaration has no initial assignment, it initializes all its variables with nil: local a, b = 1, 10 if a < b then print(a) --> 1 local a -- '= nil' is implicit(隐式) print(a) --> nil end -- ends the block started at 'then' print(a, b) --> 1 10
forth instance:
--This code creates a local variable, foo, and initializes it with the value of the global variable foo. (The local foo becomes visible only after its declaration.) local foo = foo
-------------------------------------------
Control Structures
if(conditional) while, repeat, for(iteration) terminator: end terminates if, for and while structures; until terminates repeat structures. -->Remember that Lua treats as true all values different from false and nil. (In particular, Lua treats both zero and the empty string as true.)
if then else
1
if a < 0 then a = 0 end if a < b then return a else return b end if line > MAXLINES then showpage() line = 0 end
2
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
-->Lua has no switch statement, such chains are somewhat(几分) common.
while
local i = 1 while a[i] do print(a[i]) i = i + 1 end
repeat
1
-- print the first non-empty input line repeat line = io.read() until line ~= "" print(line)
2
-->Unlike in most other languages, in Lua the scope of a local variable declared inside the loop includes the condition: local sqr = x/2 repeat sqr = (sqr + x/sqr)/2 local error = math.abs(sqr^2 - x) until error < x/10000 -- local 'error' still visible here
for
The for statement has two variants: the numeric for and the generic for.
-------------------------------------------------------------------
Numeric for
1
for var = exp1, exp2, exp3 do <something> end --This loop will execute something for each value of var from exp1 to exp2, using exp3 as the step to increment var.
2
for i = 1, f(x) do print(i) end for i = 10, 1, -1 do print(i) end
--This third expression is optional; whenabsent, Lua assumes 1 as the step value.
--(var从exp1变化到exp2,每次变化以exp3为步长递增var,并执行一次“执行体”。exp3是可选的,如果不指定,默认为1)
--(for的三个表达式在循环开始前一次性求值,以后不再进行求值。比如上面的f(x)只会在循环开始前执行一次,其结果用在后面的循环中)
3
--If you want a loop without an upper limit, you can use the constant math.huge:
for i = 1, math.huge do if (0.3*i^3 - 20*i^2 - 500 >= 0) then print(i) break end end
4 wrong show
for i = 1, 10 do print(i) end max = i -- probably wrong! 'i' here is global
correct
-- find a value in a list local found = nil for i = 1, #a do if a[i] < 0 then found = i -- save value of 'i' break end end print(found)
----------------------------------------------
Generic for
The generic for loop traverses all values returned by an iterator function:
-- print all values of table 't' for k, v in pairs(t) do print(k, v) end
generic for is powerful
days = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"}
revDays = {["Sunday"] = 1, ["Monday"] = 2,
["Tuesday"] = 3, ["Wednesday"] = 4,
["Thursday"] = 5, ["Friday"] = 6,
["Saturday"] = 7}
x = "Tuesday"
print(revDays[x]) --> 3
revDays = {}
for k,v in pairs(days) do
revDays[v] = k
end
--The loop will do the assignment for each element of days, with the variable 
k getting the key (1, 2, . . . ) and v the value (“Sunday”, “Monday”, ...).
break, return, and goto
The break and return statements allow us to jump out of a block. The goto
statement allows us to jump to almost any point in a function.
*We use the break statement to finish a loop,breaks the inner loop (for, repeat, or while)
*A return statement returns occasional results from a function or simply finishes the function.
return
1
local i = 1 while a[i] do if a[i] == v then return i end i = i + 1 end
2
function foo () return --<< SYNTAX ERROR -- 'return' is the last statement in the next block do return end -- OK <other statements> end
goto
A goto statement jumps the execution of a program to a corresponding label.
1
while some_condition do ::redo:: if some_other_condition then goto continue else if yet_another_condition then goto redo end <some code> ::continue:: end
2
while some_condition do if some_other_condition then goto continue end local var = something <some code> ::continue:: end
3
::s1:: do local c = io.read(1) if c == '0' then goto s2 elseif c == nil then print'ok'; return else goto s1 end end ::s2:: do local c = io.read(1) if c == '0' then goto s1 elseif c == nil then print'not ok'; return else goto s2 end end goto s1
--------------------------------------------------
Function
print "Hello World" --> print("Hello World") dofile 'a.lua' --> dofile ('a.lua') print [[a multi-linemessage]] --> print([[a multi-line message]])
f{x=10, y=20} --> f({x=10, y=20})
type{} --> type({})
a sum
-- add the elements of sequence 'a' function add (a) local sum = 0 for i = 1, #a do sum = sum + a[i] end return sum end
func f
function f (a, b) print(a, b) end f(3) --> 3 nil f(3, 4) --> 3 4 f(3, 4, 5) --> 3 4 (5 is discarded)
 
                     
                    
                 
                    
                 
 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号