lua list 封装

-- list索引从1开始
list = {}
list.__index = list
 
function list:new()
    local o = {}
    setmetatable(o, self)
    return o
end
 
function list:add(item)
    table.insert(self, item)
end
 
function list:clear()
    local count = self:count()
    for i=count,1,-1 do
        table.remove(self)
    end
end
 
function list:contains(item)
    local count = self:count()
    for i=1,count do
        if self[i] == item then
            return true
        end
    end
    return false
end
 
function list:count()
    return table.getn(self)
end
 
function list:get(index)
    local count = self:count()
    if (count == 0 or count < index) then
        return nil
    end
    return self[index]
end
 
 
function list:indexOf(item)
    local count = self:count()
    for i=1,count do
        if self[i] == item then
            return i
        end
    end
    return 0
end
 
function list:lastIndexOf(item)
    local count = self:count()
    for i=count,1,-1 do
        if self[i] == item then
            return i
        end
    end
    return 0
end

-- 索引index在[1,count+1]插入成功,其他位置插入会失败
function list:insert(index, item)
    table.insert(self, index, item)
end
 
-- 通过对象删除
function list:remove(item)
    local idx = self:lastIndexOf(item)
    if (idx > 0) then
        table.remove(self, idx)
        self:remove(item)
    end
end

-- 通过索引删除
function list:removeAt(index)
    table.remove(self, index)
end
 
function list:sort(comparison)
    if (comparison ~= nil and type(comparison) ~= 'function') then
        print('comparison is invalid')
        return
    end
    if comparison == nil then
        table.sort(self)
    else
        table.sort(self, comparison)
    end
end

--list声明初始化
local mylist = list:new()
mylist:add('11')
mylist:add('22')
mylist:add('33')
mylist:add('44')
mylist:add('11')

-- mylist:clear()
-- print(mylist:contains('222'))
-- print(mylist:get(0))
-- print(mylist:get(3))
--print(mylist:indexOf("11"))
--print(mylist:lastIndexOf("111"))
--mylist:insert(1, "aa")
-- mylist:remove("11")
-- mylist:removeAt("11")

-- 排序
mylist:sort(function(a,b)
    -- return a > b -- 降序
    return a < b -- 升序
end)

print("count="..mylist:count())
 
-- list for 循环
for i,v in ipairs(mylist) do
    print(i,v)
end

 

posted on 2022-09-02 11:29  Ruthless  阅读(160)  评论(0编辑  收藏  举报