朱皮特的博客 自由的飞翔

Lua的表table

2013-03-17
朱皮特
lua
阅读量:

格式化输出表数据

function table2str(t)
    local s = 't = {\n'
    for key,value in pairs(t) do
        s = s..'\''..value..'\',\n'
    end
    s = s..'}'
    star.log(s, 't.txt')
end

排序

table.sort (table [, comp])

Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the length of the table. If comp is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead. The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.

name = {"you" ,"me", "him","bill" }
--table.sort - only works with arrays!
table.sort(name)
for k, v in ipairs( name) do
    print( k,v)
end
--table.sort uses callbacks. a function that is writtent to be called by a library function.
function cmp( a, b)
    if string.sub(a,2 ,2) < string.sub(b,2 ,2) then
        return true
    else
        return false
    end
end

table.sort(name, cmp)
for k, v in ipairs( name) do
    print( k,v)
end
network = {
{name = "grauna" ,  IP = "210.26.30.34"},
{name = "arraial", IP = "210.26.30.23"},
{name = "lua" ,  IP =  "210.26.23.12"},
{name = "derain" ,  IP = "210.26.23.20"},}

--如果我们想通过表的name域排序:
table.sort(network,  function(a,b) return (a.name > b.name) end)

Comments

Content