加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

推词典?如何在Lua中实现这一目标?

发布时间:2020-12-14 21:44:16 所属栏目:大数据 来源:网络整理
导读:说我在Lua有这本字典 places = {dest1 = 10,dest2 = 20,dest3 = 30} 在我的程序中,我检查字典是否符合我在这种情况下的大小限制3,如何从字典中推出最旧的键/值对并添加一个新的? places["newdest"] = 50--places should now look like this,dest3 pushed of
说我在Lua有这本字典

places = {dest1 = 10,dest2 = 20,dest3 = 30}

在我的程序中,我检查字典是否符合我在这种情况下的大小限制3,如何从字典中推出最旧的键/值对并添加一个新的?

places["newdest"] = 50

--places should now look like this,dest3 pushed off and newdest added and dictionary has kept its size

places = {newdest = 50,dest1 = 10,dest2 = 20}

解决方法

如果你真的需要它,这并不难做到,而且它也很容易重复使用.

local function ld_next(t,i) -- This is an ordered iterator,oldest first.
  if i <= #t then
    return i + 1,t[i],t[t[i]]
  end
end

local limited_dict = {__newindex = function(t,k,v)
  if #t == t[0] then -- Pop the last entry.
    t[table.remove(t,1)] = nil
  end
  table.insert(t,k)
  rawset(t,v)
end,__pairs = function(t)
  return ld_next,t,1
end}

local t = setmetatable({[0] = 3},limited_dict)

t['dest1'] = 10
t['dest2'] = 20
t['dest3'] = 30
t['dest4'] = 50

for i,v in pairs(t) do print(k,v) end
dest2   20
dest3   30
dest4   50

订单存储在数字索引中,第0个索引指示表可以具有的唯一键的限制.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读