A set is an unordered collection of unique values. Unlike an array or a list, it is very efficient at testing whether a value is currently stored in the set or not, without having to check every item.

local set = require "util.set"; local myset = set.new(); myset:add("red"); print(myset:contains("red")); --> true print(myset:contains("blue")); --> false

Creates and returns a new set. You can optionally supply a `list`

(or anything that can be iterated using `ipairs()`

)

For example:

-- Creating an empty set local myset = set.new(); -- Creating a set from an existing list local colours = set.new({ "red", "blue", "yellow", "green" }); print(colours:contains("purple")) --> false print(colours:contains("yellow")) --> true

Creates and returns a new set that contains all the items in set1 and all the items in set2.

Creates and returns a new set that contains all the items in set1 that are not in set2.

Creates and returns a new set that contains only the items that are in both set1 and in set2.

Creates and returns a new set that contains only the items are in set1 or set2. Items that are in both sets will not be included.

Once a set is created, you can use these methods on them.

Adds a value to the set. Any Lua value is acceptable, apart from nil.

Removes a value from the set.

Tests whether a value is currently in the set. Returns true if it is, or nil otherwise.

Adds a list of values (a normal Lua array, util.array object, or anything that can be iterated using `ipairs()`

) to the set.

Adds all the values from another set to this set.

Removes from this set all the values that another set contains.

Returns true if the set contains no values. Otherwise returns false.

Returns the underlying data structure, a table with all the item values as keys, and boolean `true`

as a value.

Adding two sets results in their union:

superset = set1 + set2 -- is the same as superset = set.union(set1, set2)

Subtracting a set results in their difference:

newset = set1 - set2 -- is the same as newset = set.difference(set1, set2)

You can divide a set by a filter function, to produce a new set. The function is called once for each item, with the value as its first parameter. If the function does not return nil, the item is added to the new set.

-- Returns true if the given number is even, or false if it is odd: local function is_even(number) if number%2 == 0 then return true; end end print(is_even(1), is_even(2), is_even(3), is_even(4)); --> false, true, false, true, etc. local numbers = set.new({ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); local even_numbers = numbers / is_even; print(even_numbers); --> 2, 4, 6, 8, 10