重回Lua - Table

2021-01-23  本文已影响0人  IvanRunning
t = {6,7,8,9}
--上面和下面的代码等价
t = {
    [1] = 6,
    [2] = 7,
    [3] = 8,
    [4] = 9,
}
--甚至你可以跳过某些下标
t = {
    [1] = 6,
    [3] = 7,
    [5] = 8,
    [7] = 9,
}
print(t[7])
--输出9

--在声明后赋予元素值也是可以的
t = {}--空的table
t[101] = 10
print(t[101])
t = {
    ["apple"] = 10,
    banana = 12,
    pear = 6,
}

--使用["下标"] = 值
--和  下标 = 值
--都是正确写法
--当第二种方式有歧义时,应该用第一种方式

--可以用下面两种方式访问:
print(t["apple"])
--输出10
print(t.apple)
--输出10
--当第二种方式有歧义时,应该用第一种方式
[[万物皆Table]]
n = 123--新建变量
print(n)--输出123
print(_G.n)--输出123

_G.abc = 1--相当于新建全局变量
print(abc)--输出1

_G["def"] = 23--相当于新建全局变量
print(def)--输出23

--甚至你可以像下面这样
_G.print("hello")
_G["print"]("world")

table.concat (table [, sep [, i [, j ] ] ])
将元素是string或者number类型的table,每个元素连接起来变成字符串并返回。
可选参数sep,表示连接间隔符,默认为空。
i和j表示元素起始和结束的下标。

[[Table 方法]]
local a = {1, 3, 5, "hello" }
print(table.concat(a))
print(table.concat(a, "|"))
-->打印的结果:
--135hello
--1|3|5|hello

table.insert (table, [pos ,] value)
在(数组型)表 table 的 pos 索引位置插入 value,其它元素向后移动到空的地方。pos 的默认值是表的长度加一,即默认是插在表的最后。
table.remove (table [, pos])
适用数组的情况
在表 table 中删除索引为 pos(pos 只能是 number 型)的元素,并返回这个被删除的元素,它后面所有元素的索引值都会减一。pos 的默认值是表的长度,即默认是删除表的最后一个元素。

local a = {1, 8}             --a[1] = 1,a[2] = 8
table.insert(a, 1, 3)   --在表索引为1处插入3
print(a[1], a[2], a[3])
table.insert(a, 10)    --在表的最后插入10
print(a[1], a[2], a[3], a[4])

-->打印的结果:
--3    1    8
--3    1    8    10

local a = { 1, 2, 3, 4}
print(table.remove(a, 1)) --删除速索引为1的元素
print(a[1], a[2], a[3], a[4])

print(table.remove(a))   --删除最后一个元素
print(a[1], a[2], a[3], a[4])

-->打印的结果:
--1
--2    3    4    nil
--4
--2    3    nil    nil
上一篇 下一篇

猜你喜欢

热点阅读