Lua


table 函数库

concat

table.concat(table, sep=’ ‘, start=1, end=nSize)

> tbl = {"alpha", "beta", "gamma"}
> print(table.concat(tbl, ":"))
alpha:beta:gamma
> print(table.concat(tbl, nil, 1, 2))
alphabeta
> print(table.concat(tbl, "\n", 2, 3))
beta
gamma

foreach

table.foreach(table, function(i, v)) 迭代整个 table 进行 funtion(i, v) 操作.

t1 = {2, 4, 6, language="Lua", version="5", 8, 10, 12, web="hello lua"};
table.foreach(t1, function(i, v) print (i, v) end) ;

输出结果:

1 2
2 4
3 6
4 8
5 10
6 12
web hello lua
language Lua
version 5

foreachi

table.foreachi(table, function(i, v)) 对 table 中 key 值从 1 开始的连续整数范围迭代进行 function(i, v) 操作.

t1 = {2, 4, 6, language="Lua", version="5", 8, 10, 12, web="hello lua"};
table.foreachi(t1, function(i, v) print (i, v) end) ; --等价于 foreachi(t1, print)

输出结果:

1 2
2 4
3 6
4 8
5 10
6 12

getn

table.getn(table) 返回 table 中元素的个数

t1 = {1, 2, 3, 5};
print(table.getn(t1)) -- eq print(#t1)
>4

insert

table.insert(table, pos=nSize, value)

> tbl = {"alpha", "beta", "gamma"}
> table.insert(tbl, "delta")
> table.insert(tbl, "epsilon")
> print(table.concat(tbl, ", ")
alpha, beta, gamma, delta, epsilon
> table.insert(tbl, 3, "zeta")
> print(table.concat(tbl, ", ")
alpha, beta, zeta, gamma, delta, epsilon

maxn

table.maxn(table) 函数返回指定 table 中所有正数 key 值中最大的 key 值. 如果不存在 key 值为正数的元素, 则返回 0. 此函数不限于 table 的数组部分.

> tbl = {[1] = "a", [2] = "b", [3] = "c", [26] = "z"}
> print(#tbl)
3               -- 因为 26 和之前的数字不连续, 所以不算在数组部分内
> print(table.maxn(tbl))
26
> tbl[91.32] = true
> print(table.maxn(tbl))
91.32

remove

table.remove(table, pos=nSize)

> t1 = {1, 2, 3, 5};
> print(table.remove(t1, 1))
1
> print(table.remove(t1))
5

sort

table.sort(table, comp=ASC)

> tbl = {"alpha", "beta", "gamma", "delta"}
> table.sort(tbl)
> print(table.concat(tbl, ", "))
alpha, beta, delta, gamma
> sortFunc = function(a, b) return b < a end
> table.sort(tbl, sortFunc)
> print(table.concat(tbl, ", "))
gamma, delta, beta, alpha
> guild = {}
> table.insert(guild, {
>  name = "Cladhaire",
>  class = "Rogue",
>  level = 70,
> })
> table.insert(guild, {
>  name = "Sagart",
>  class = "Priest",
>  level = 70,
> })
> table.insert(guild, {
>  name = "Mallaithe",
>  class = "Warlock",
>  level = 40,
> })
> function sortLevelNameAsc(a, b)
>  if a.level == b.level then
>   return a.name < b.name
>  else
>   return a.level < b.level
>  end
> end
> table.sort(guild, sortLevelNameAsc)
> for idx, value in ipairs(guild) do print(idx, value.name) end
1, Mallaithe
2, Cladhaire
3, Sagart