随笔 - 1357  文章 - 0  评论 - 1104  阅读 - 1941万

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   Ruthless  阅读(194)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
历史上的今天:
2019-09-02 maven添加本地包命令mvn install:install-file
2019-09-02 Mysql——查看数据库,表占用磁盘大小
2017-09-02 Disruptor多个消费者不重复处理生产者发送过来的消息
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示