table中的函数

来源:互联网 发布:淘宝售前客服好做吗 编辑:程序博客网 时间:2024/04/30 08:23

table.concat(tb,sep,start,end)

concat是concatenate的缩写(连接,连锁)table.concat()列出tb中数字部分start到end部分的所有元素,其间可以用sep分隔。出了table以外,其他三个参数不是必须的,sep默认是空字符串,start为1,end为table的数组部分的长度。

sep、start、end虽然不是必须的参数,但是如果指定了靠后的参数,必须同时指定前面的参数。

tb={"imust",2,3,x="weiyu",5,6,y="like",7,8};

print("{"..table.concat(tb,",").."}";     ---输出{imust,2,3,5,6,7,8} 没有x=“weiyu"和y="like",因为这两项不是table的数组部分

table.insert(tb,pos,value)

table.insert()是在tb的指定pos插入一个value(可以是任何东西,如表),pos可选,默认是tb 的尾部。。

tb={"imust",2,3,x="weiyu",5,6,y="like",7,8}

table.insert(tb,"beyond")

print("{"..table.concat(tb,",").."}")   --{imust,2,3,5,6,7,8,beyond}

table.insert(tb,1,"beyond")

print("{"..table.concat(a,",").."}")   --{beyond,imust,2,3,5,6,7,8}

b={"hello imust.cn"}

table.insert(tb,1,b)

for k,v in pairs(tb) do

    if type(v) == "table" thend

       for kk, vv in pairs(v) do

           print("k:"..kk.."  v:"..vv)

       end

    else

        print("k:"..k.."  v:"..v)

    end

end           --先遍历表b在遍历表tb

table.maxn(tb)

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

tb={"imust",2,3,x="weiyu",5,6,y="like",7,8,[11]=11}

print(#tb)    --7        {[1]="imust",[2]=2,[3]=3,[4]=5,[5]=6,[6]=7,[7]=8}   [11]和之前的数组部分不连续,所有不算在数组部分。

print(table.maxn(tb))   --11         {[11]=11}

table.remove(tb,pos)

table.remove(tb,pos)从tb中指定的pos删除并返回table中数组部分pos位置的元素,其后的元素被前移,pos可选,默认从表的末尾删除。

tb={"imust",2,3,x="weiyu",5,6,y="like",7,8}

print(table.remove(tb))   --返回删除位置的元素  8

table.sort(tb,comp)

table.sort()对指定的表进行升序排序。

a={"imust","3","2",x="yu","5",z="wei"}

print("{"..table.concat(a,",".."}")   --{imust,3,2,5}

table.sort(a)  --升序排序

print("{"..table.concat(a,",").."}")  --{2,3,5,imust}  非数组部分不进行排序(不连续的数组也不排序)

comp是可选参数,是外部函数,定义排序标准。

此函数应该满足以下条件:接受2个参数(a,b)返回一个bool,当a应该排在b前面时返回true,反之返回false。

如降序排序

a={"imust","3","2",x="yu","5",z="wei"}

comp=functin(a,b) return b<a end     --b>a为升序,可以构造出更复杂的排序函数

table.sort(a,comp)

print("{"..table.concat(a,",").."}")   --{imust,5,3,2}

 

原创粉丝点击