跳转至

学习笔记

表格#

变量默认为全局变量,而全局变量存储在普通表中。

数组、列表和序列都用表表示。

构造器#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
-- 默认整数索引
days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
print(days[4])  --> Wednesday

-- identifier索引
a = {x = 10, y = 20}

-- 空
a = {}; a.x = 10; a.y = 20 --长度不固定,因而较慢

-- 复合索引
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]
            }

-- 方括号通用索引(字符串不限于identifier)
opnames = {["+"] = "add", ["-"] = "sub", ["*"] = "mul", ["/"] = "div"}
a = {["x"] = 0, ["y"] = 0}
b = {[1] = "r", [2] = "g", [3] = "b"}

-- 最后一项后可以用逗号
a = {[1] = "red", [2] = "green", [3] = "blue",}

遍历#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
t = {10, print, x = 12, k = "hi"}
for k, v in pairs(t) do
    print(k, v)
end
--> 1    10
--> k    hi
--> 2    function: 0x420610
--> x    12

-- 遍历整数索引
t = {10, print, 12, "hi"}
for k, v in ipairs(t) do
    print(k, v)
end
--> 1    10
--> 2    function: 0x420610
--> 3    12
--> 4    hi

安全导航#

1
2
3
4
5
6
7
8
9
-- 通常如此
zip = company and company.director and
    company.director.address and
    company.director.address.zipcode

-- 模仿其他语言的安全运算符`?.`
-- zip = company?.director?.address?.zipcode
E = {}     -- can be reused in other similar expressions
zip = (((company or E).director or E).address or E).zipcode

dofile#

加载程序chunk

1
dofile("chunk.lua");

评论