local usertable = {}
--添加一个元素
function AddUser(user_id)
if(usertable[user_id] ~= nil) then
return false
end
usertable[user_id] = 1
return true
end
--删除一个元素
function RmUser(user_id)
if(usertable[user_id] ~= nil) then
usertable[user_id] = nil
return true
end
return false
end
--迭代器
function pairsByKeys(t)
local a = {}
for n in pairs(t) do
a[#a+1] = n
end
table.sort(a)
local i = 0
return function()
i = i + 1
return a[i], t[a[i]]
end
end
--获取元素个数
function getUserCount()
local userCount = 0
for key,value in pairsByKeys(usertable) do
if (value ~= nil) then
userCount = userCount + 1
print(string.format("value[%d]=%d",key,value))
end
end
return userCount
end
--测试
function test()
local count = getUserCount()
print("==========init result:"..count)
AddUser(111);
AddUser(234);
count = getUserCount()
print("=========then result:"..count)
RmUser(111);
count = getUserCount()
print("=====then result:"..count)
AddUser(112);
count = getUserCount()
print("====last result:"..count)
end
--测试
test()