lua数组表格处理(table库用法)

原文地址http://www.freecls.com/a/2712/10

table库由一些基本函数组成来以数组的形式(也就是只能处理数字下标的元素)处理表格包括插入移除排序连接所有元素为字符串

table.insert (table, [pos,] value)

插入数据,pos为插入的位置,省略pos默认从表格最后插入

例子

local res,t
t = {'freecls'}

--{'freecls','com'}
table.insert(t,'com')

--{'www','freecls','com'}
table.insert(t,1,'www')


table.remove (table [, pos])

从pos处移除数据,默认移除最后一个

例子

local res,t

t = {'111','www','freecls','com','222',name='freecls'}

--{'111','www','freecls','com',name='freecls'}
table.remove(t)

--{'www','freecls','com',name='freecls'}
table.remove(t,1)


table.concat (table [, sep [, i [, j]]])

把数组连接成字符串连接符为sep(默认为空字符)

例子

local res,t,s

t = {'www','freecls','com'}

--wwwfreeclscom
local s = table.concat(t)

--www.freecls.com
local s = table.concat(t,'.')


table.sort (table [, comp])

数组排序,comp为可选回调函数,默认用<比较

例子

local res,t,s

local t = {33,1,10,2,22}

--{1,2,10,22,33}
table.sort(t)


--排序复杂数据
t = {}
table.insert(t,{s='www',num=22})
table.insert(t,{s='freecls',num=24})
table.insert(t,{s='com',num=10})

function cmp(t1,t2)
    if t1.num <= t2.num then
        return true
    else
        return false
    end
end

--{{s='com',num=10},{s='www',num=22},{s='freecls',num=24}}
table.sort(t,cmp)


总结 

1.本文只是对table库做简单的介绍,如果有疑问可以给我留言
2.lua的版本为5.1,运行环境centos7 64位
3.原文地址http://www.freecls.com/a/2712/10

猜你喜欢

转载自blog.csdn.net/freecls/article/details/80264451