It's annoying that Lua doesn't have proper support for sets, requiring slightly ugly use of tables.
To this end, hopefully people can get some use out of this: https://www.roblox.com/library/2679565467/HashSet
It's not perfect, because Lua lacks proper static typing and ROBLOX is running an old verison of Lua which would let it work a little bit more nicely, and Lua requiring to implement OOP by yourself is an absolute joke, etc...
Also the in-script commenting is bad.
Basic implementation of a hash-set in Lua.
Create an empty set with
.new, or create one from an array with
Check for presence in a set with
:contains. Add or remove elements with
:remove. Cardinality (size) of the set can be retrieved with
Element-by-element equality can be checked with
:equals, or alternatively, an overload of
== is provided, so
set1 == set2 is valid. Frankly, when even Lua can provide operator overloading, it's a bit embarrasing when a language can't (looking at you, Java). Overloading of
+ is not provided, because it'd be ambiguous whether you meant intersect or union. Overloading of
- isn't provided because it'd be a bit weird providing
- but not
pairs() use is not possible since ROBLOX is running an old version of Lua. As an alternative, you need to call
for value in set:pairs() do. Note the absence of the second field - it's a set.
Union and intersect operations are performed in-place with
:minus is in-place, and calculates the relative set complement of two sets. "In-place" just means it doesn't return a new set: it modifies the old one.
Obviously, being in-place is a bit annoying sometimes, so
:copy can be used to create a shallow copy of the set.
Finally, as a nice little bonus, this class implements
__tostring, so printing it actually gives you a real result rather than the mess Lua gives you by default. How hard is it for a language to provide a decent tostring for a data structure when said languages has literally only 1 data structure?
That's basically it. Contact me if you have any questions.