【问题标题】:Push dictionary? How to achieve this in Lua?推字典?如何在 Lua 中实现这一点?
【发布时间】:2014-01-13 13:15:07
【问题描述】:

假设我有这本 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}

【问题讨论】:

  • 你为什么要这个?
  • 字典键不按你输入的顺序保存,不像索引,所以我不知道你能不能把它推到前面。你/可以/用一个索引表来做(在意识到你想要字典之前我写了一个函数)。
  • @lhf 仅用于编写游戏脚本,我需要一个具有固定大小的字典,并在添加新对时推出最旧的键/值对(一旦达到固定大小)。

标签: dictionary lua lua-table


【解决方案1】:

如果您真的需要它,这样做并不太难,而且它也很容易重复使用。

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, k, 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, k, v in pairs(t) do print(k, v) end
目的地2 20 目标3 30 目的地4 50

顺序存储在数字索引中,0th 索引指示表可以拥有的唯一键的限制。

【讨论】:

  • 谢谢,这对我来说最简单。虽然有些有点过头了,所以我有点盲目地使用它,呵呵。
【解决方案2】:

鉴于字典键不保存其输入的位置,我写了一些东西应该能够帮助你完成你想要的,无论如何。

function push_old(t, k, v)
  local z = fifo[1]
  t[z] = nil
  t[k] = v
  table.insert(fifo, k)
  table.remove(fifo, 1)
end

您需要先创建 fifo 表,根据您输入键的顺序(例如,fifo = {"dest3", "dest2", "dest1"},根据您的帖子,从第一次输入到最后输入),然后使用:

push_old(places, "newdest", 50)

该功能将完成工作。节日快乐!

【讨论】:

  • 为什么要在fifo_push新建表?
  • 由于 fifo 是输入值的索引表,我想我认为我重建它的方式对于“先进先出”模型来说是最有利的方式。现在编辑它以获得更清洁的功能。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-12
  • 1970-01-01
  • 2022-08-21
相关资源
最近更新 更多