说我在Lua有这本字典 places = {dest1 = 10, dest2 = 20, dest3 = 30} 在我的程序中,我检查字典是否符合我在这种情况下的大小限制3,如何从字典中推出最旧的键/值对并添加一个新的? places["newdes
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, 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
订单存储在数字索引中,第0个索引指示表可以具有的唯一键的限制.