Click dictionary? How to achieve this in Lua?

Say I have this dictionary in Lua

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

In my program, I check if the dictionary matches my size limit in this case 3, how can I get the oldest key / value pair from the dictionary and add a new one?

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}
+4
source share
2 answers

This is not too difficult to do if you really need it, and it can be easily reused.

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
dest2 20
dest3 30
dest4 50

The order is stored in numerical indexes with an index 0th indicating the limit of the unique keys that the table can have.

+3
source

, , -, , , .

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)

. !

0

All Articles