I use this data structure all the time. Can someone leave a comment and tell me what it's called?
- insert(k,v): add a new value
- lookup(k): lookup an existing value
- age(): delete old entries (that have not been used since previous call to age())
# Initialize 'old' and 'new' to empty tables
local old, new = {}, {}
function insert(k, v)
new[k] = v
end
function lookup(k)
if new[k] then
# Found in new table
return new[k]
elseif old[k] then
# Migrate from old table to new table
new[k] = old[k]
return old[k]
else
# Not found
return nil
end
end
function age()
# Entries in 'old' are dropped, entries in 'new' become old.
old = new
new = {} # empty table
end
I suppose it's good that Lua distinguishes between statements and expressions, because otherwise I wouldn't be able to resist this 4-liner version: