5 min

A set is a collection of items with no order and no duplicate elements — in other words, an item either is or is not contained within a set. Using articles/Metatables|metatables, you can construct and manipulate sets within Lua scripts.

Basic Methods

The following code includes basic set functionality, letting you construct new sets, add/remove an item, check if a set contains an item, and output the contents of a set.

Create Set

A new set can be constructed by calling Set.new() with an optional array of items to add.

Add Item

Adding an item to an existing set can be done via the Set:add() method.

Remove Item

To remove an item from a set, call Set:remove() with the item name.

Check for Item

To check if a set contains a specific item, use Set:contains().

Additional Methods

Other useful operations can be implemented for sets, letting you compare items between sets, combine sets, or subtract one set from another.


When considering sets as venn diagrams, you can get the intersection of two sets as follows, meaning the items that appear in both sets.


You can get the union of two sets with the following function, meaning a collection of the items in both sets with no duplicates. Note that this function uses the metatable __add method to provide an addition shortcut of set1 + set2.


You can remove all items in one set from the items in another set via the following function. Similar to the function above, this uses the metatable __sub method to provide a subtraction shortcut of set1 - set2.

  • lua
  • set
  • collection