Lua初识之表的构造
构造器是创建初始化表的表达式,表是Lua特有的功能强大的东西,最简单的构造函数是{}, 用来创建一个空表。可以直接出示化数组。
days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
构造一个 days 表并初始化 (第一个元素索引为 1)
print(days[1]) -- Sunday
print(days[2])
print(days[3])
构造函数可以使用任何表达式初始化
tab = { math.sin(1), math.sin(2), math.sin(3), math.sin(4),
math.sin(5)}
print(tab[1])
print(tab[2])
赋值型
a = {x = 2, y = 3}
print(a["x"]) -- 取值需要用双引号
print(a["y"]) --
--嵌套表
--[[
polyLine =
{ color = "blue", thickNess = 2, point = 4,
{ x = 0, y = 0},
{ x = 1, y = 1},
{ x = 2, y = 2},
{ x = 3, y = 3}
}
print(polyLine["color"]) --> blue
print(polyLine[1].color) --> nil
print(polyLine[2]) --> table:012BB8A8
print(polyLine[1].x) --> 0
print(polyLine[2].x) --> 1
--]]
--[[opnames = { ["+"] = "add", ["-"] = "sub"}
i = 20; s = "-"
a = { [i + 0] = s, [i + 1] = s .. s, [i + 2] = s .. s .. s}
print(opnames[s]) --> sub
print(a[20]) --> - 取值不用双引号
print(a[22]) --> -----]]
--[[
n1 = { x = 0, y = 0} -- n1 n2 等价
-- 最好不要用数组下标从 0 开始,否则好多标准库用不了
n2 = { ["x"] = "10", ["y"] = "10"}
print(n1["x"]) -- 0
print(n1["y"]) -- 0
print(n2["x"]) -- 10
print(n2["y"]) -- 10--]]
m1 = {"red", "green", "blue"} -- m1 m2 等价
m2 = {[1] = "red", [2] = "green", [3] = "blue"}
print(m1[1]) -- red
print(m1[2]) -- green
print(m1[3]) -- blue
print(m2[1]) -- red
print(m2[2]) -- green
print(m2[3]) -- blue
Lua初识之表的构造-六
最新推荐文章于 2024-08-06 22:45:06 发布