Lua 教程 在线

2058Lua table(表)

排序支持自定义排序规则,比如:

t =
{
    [1] = {A = 5, B = 2},
    [2] = {A = 1, B = 3},
    [3] = {A = 3, B = 6},
    [4] = {A = 7, B = 1},
    [5] = {A = 2, B = 9},
}
table.sort(t, function(a, b) return a.A > b.A; end)

2057Lua table(表)

-- table 去重
table = {1 , 2 , 3 , 4 , 20 , 6 , 7 , 7 , 15 , 28};
function table_unique(t) 
    local check = {};
    local n = {};
    for key , value in pairs(t) do
        if not check[value] then
            n[key] = value
            check[value] = value
        end
    end
    return n
end 

for key , value in pairs(table_unique(table)) do
    print('value is ' , value)
end

2056Lua table(表)

数组去重

--数组去重函数
function removeRepeat(a)
    local b = {}
    for k,v in ipairs(a) do
        if(#b == 0) then
            b[1]=v;
        else
            local index = 0
            for i=1,#b do
                if(v == b[i]) then
                    break

                end
                index = index + 1
            end
            if(index == #b) then
                b[#b + 1] = v;
            end
        end
    end
    return b
end

--遍历数组输出
function output(o)
    for k,v in ipairs(o) do
        print(k,v)
    end
end

--测试
arr = {1,1,1,2,4,5,3,2,5,3,6}
narr = removeRepeat(arr)
table.sort(narr)  --对数组排序
output(narr)

结果:

1    1
2    2
3    3
4    4
5    5
6    6

2055Lua table(表)

table 去重

function table.unique(t, bArray)
    local check = {}
    local n = {}
    local idx = 1
    for k, v in pairs(t) do
        if not check[v] then
            if bArray then
                n[idx] = v
                idx = idx + 1
            else
                n[k] = v
            end
            check[v] = true
        end
    end
    return n
end

2054Lua 迭代器

字符串分割函数:

function split(str,delimiter)
    local dLen = string.len(delimiter)
    local newDeli = ''
    for i=1,dLen,1 do
        newDeli = newDeli .. "["..string.sub(delimiter,i,i).."]"
    end

    local locaStart,locaEnd = string.find(str,newDeli)
    local arr = {}
    local n = 1
    while locaStart ~= nil
    do
        if locaStart>0 then
            arr[n] = string.sub(str,1,locaStart-1)
            n = n + 1
        end

        str = string.sub(str,locaEnd+1,string.len(str))
        locaStart,locaEnd = string.find(str,newDeli)
    end
    if str ~= nil then
        arr[n] = str
    end
    return arr
end    
t = split("php,js", ",")
for k, v in pairs(t) do
    print(k, v)
end

执行输出结果为:

1 php
2 js

欢迎指教讨论。