跳转至

学习笔记

表格#

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

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

构造器#

-- 默认整数索引
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",}

遍历#

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

安全导航#

-- 通常如此
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

评论