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

lua map 封装

复制代码
map = {}

local this = map

function this:new()
    o = {}
    setmetatable(o,self)
    self.__index = self
    self.count = 0
    return o
end

-- put在放入数据时,如果放入数据的key已经存在Map中,最后放入的数据会覆盖之前存在的数据
function this:put(k,v)
    if nil == self[k] then
        --table.put(self,{a = b})
        self.count = self.count + 1
    end
    self[k] = v
end

-- putIfAbsent在放入数据时,如果存在重复的key,那么putIfAbsent不会放入值
function this:putIfAbsent(k,v)
    if nil == self[k] then
        --table.put(self,{a = b})
        self[k] = v
        self.count = self.count + 1
    end
end

function this:remove(k)
    if nil ~= self[k] then
        self[k] = nil
        if self.count >0 then
            self.count = self.count - 1
        end
    end
end

function this:get(k)
    local value = nil
    if nil ~= self[k] then
        value = self[k]
    end
    return value
end

function this:clear()
    for k,_ in pairs(self) do
        if nil ~= self[k] then
            self[k] = nil
        end
    end
    self.count = 0
end

--[[
-- map测试案例
local characters = map:new()

characters:putIfAbsent("username", "张三aa")
characters:putIfAbsent("username", "张三bb")
characters:put("password", "123456")
characters:put("salt", "111111")
characters:remove("password")
characters:put("age", 20)

local username = characters:get("username")
print("username="..username)
local age = characters:get("age")
print("age="..age)


print("count="..characters.count)

characters:clear()
for k,v in pairs(characters) do
    print(k,v)
end

--]]
复制代码

 

posted on   Ruthless  阅读(140)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
历史上的今天:
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

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