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 2022-09-02 11:28  Ruthless  阅读(107)  评论(0编辑  收藏  举报