I’m using Lua tables as sets by placing the value of the set in the table key and 1 as the table value, e.g.
function addToSet(s,...) for _,e in ipairs{...} do s[e]=1 end end
function removeFromSet(s,...) for _,e in ipairs{...} do s[e]=nil end end
local logics = {}
addToSet(logics,true,false,"maybe")
To test if two sets are equal I need to ensure that they have exactly the same keys. What’s an efficient way to do this?
Loop through both tables and make sure that the key has a value in the other. Fail as soon as you find a mismatch, return
trueif you got through both. For sets of sizeMandNthis is O(M+N) complexity.Seen in action:
Note testing for
t[k]==nilis better than justnot t[k]to handle the (unlikely) case that you have set a value offalsefor the table entry and you want the key to be present in the set.