-
Notifications
You must be signed in to change notification settings - Fork 0
Set
The Set library provides a basic implementation of a set data structure in Lua. It allows you to create sets, add and remove elements, get the size of the set, and clone sets.
Why use a set? A set is great when all you need to know is if an object is true or false.
Imagine you run a Gym with hudreds of thousands of members. When a member comes in, they need to show a card that holds a unique id for them.
If you were to add it to a standard list, then you'd have to loop through up to all hundreds of thousands of members to see if the member is still active. This is slow and wasteful.
With a set you can directly look him up.
local uniqueID = members[scannedID]
-- Instantly gets if the member is active or not. No loops needed.There are two ways to create a set.
- The Tablua Generic method
- Directly from set.lua
-- Option 1) From Tablua
local Tablua = require "Tablua"
local mySet = Tablua.Set() -- This is the exact same as option 2
-- Option 2) From set.lua
local Set = require "Tablua.set"
local mySet = Set.new()All below expect option 1 has already been done.
This simply adds an element to the set.
-- Usage
mySet:add("element")Removes an item from the set.
mySet:remove("element")This will return the total number of items inside the set. Note that to ensure quick runtime of this method, adding "__SIZEOFSETPROTECTEDVARIABLENAMESPACE__" is not allowed and will error.
mySet:add(1)
mySet:add(2)
print(mySet:size()) -- prints 2Makes a copy of the set and returns the copy.
mySet = Tablua.Set()
mySet:add("Hello")
mySet:add("World")
secondSet = mySet:clone()
print(secondSet["Hello"]) -- prints true
print(secondSet["World"]) -- prints true
-- these are separated sets
mySet:remove("Hello")
print(secondSet["Hello"]) -- prints true despite being removed from it's original set.As alluded to above, the way to get if the key is populated is as such
mySet:add("Hello")
print(mySet.Hello) -- true
print(mySet["Hello"]) -- true
print(mySet.hello) -- false; sets are case sensitive.That's all you need to know to use the Set library in your Lua projects. Enjoy!