Lua中的table函数库整理与实践

2014-2-12 杜世伟 Lua

Lua table库由一些操作table的辅助函数组成。他的主要作用之一是对Luaarray的大小给出一个合理的解释。另外还提供了一些从list中插入删除元素的函数,以及对array元素排序函数。

Lua中是没有array概念的,不过可以通过tabel数据结构实现对array的操作。以下是lua提供的函数,可能版本不同支持的函数也有所不同了

table.concat(table, sep,  start, end) concatconcatenate(连锁, 连接)的缩写. table.concat()函数列出参数中指定table的数组部分从start位置到end位置的所有元素, 元素间以指定的分隔符(sep)隔开。除了table, 其他的参数都不是必须的, 分隔符的默认值是空字符, start的默认值是1, end的默认值是数组部分的总长.sep, start, end这三个参数是顺序读入的, 所以虽然它们都不是必须参数, 但如果要指定靠后的参数, 必须同时指定前面的参数.

tmp = {1,3,4,5,7}
print(table.concat(tmp)); --13457
print(table.concat(tmp,'_')); --1_3_4_5_7
print(table.concat(tmp,'_',2,4)); --3_4_5

table.insert(table, pos, value)

table.insert()函数在table的数组部分指定位置(pos)插入值为value的一个元素. pos参数可选, 默认为数组部分末尾.

tmp = {1,3,4,5,7}
table.insert(tmp,2,2); -- 在第二个位置插入2,因为lua语言中数组下标从1开始

print(table.concat(tmp,','));   -- 1,2,3,4,5,7
 

table.remove(table, pos)

table.remove()函数删除并返回table数组部分位于pos位置的元素. 其后的元素会被前移. pos参数可选, 默认为table长度, 即从最后一个元素删起.


table.maxn(table)

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

tmp = {1,3,4,5,7}
print(table.maxn(tmp)); --5

table.sort(table, comp)

table.sort()函数对给定的table进行升序排序

tmp = {1,3,4,5,7}
table.sort(tmp);
print(table.concat(tmp,',')); -- 1,3,4,5,7

如果想实现倒序的话,可以自己下个函数

--[[
tmp 将要操作的表
comtype 排序类型
]]--
table.sorts = function(tmp,comtype)
	table.sort(tmp,function(a,b)
		if comtype == "asc" then 
			return a < b; 
		else
		    return a > b;
		end
	end);
end 
table.sorts(tmp,'asc');
print(table.concat(tmp,',')); --1,3,4,5,7

table.sorts(tmp,'dsc'); 
print(table.concat(tmp,',')); --7,5,4,3,1

table.foreachi(table, function(i, v))

会期望一个从 1(数字 1)开始的连续整数范围,遍历table中的key和value逐对进行function(i, v)操作

table.foreachi(t1, function(i, v) print (i, v) end) ; --等价于foreachi(t1, print)


table.foreach(table, function(i, v))

与foreachi不同的是,foreach会对整个表进行迭代


table.getn(table)

返回table中元素的个数

我使用的lua版本是

[root@localhost ~]# lua -v

Lua 5.2.3  Copyright (C) 1994-2013 Lua.org, PUC-Rio

今天在通过table.getn获取元素个数的时候提示: attempt to call field 'getn' (a nil value),估计是这个版本不支持getn方法了

table.getn = function(tmp)
        for i=1,math.huge do
--if tmp[i] == nil then return i-1 end
if rawget(tmp,i) == nil  then return i-1 end
        end
        return 0;
end
tmp={1,3,4,6,9}
print(table.getn(tmp)); --5

table.setn(table, nSize)

设置table中的元素个数

标签: lua table table.setn table.getn table.remove table.sort

Powered by emlog 沪ICP备2023034538号-1