Skip to content
JJSax edited this page May 18, 2023 · 1 revision

Set Library

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 and When to use

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.

Usage

There are two ways to create a set.

  1. The Tablua Generic method
  2. 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.

API Reference

Set:add

This simply adds an element to the set.

-- Usage
mySet:add("element")

Set:remove

Removes an item from the set.

mySet:remove("element")

Set:size

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 2

Set:clone

Makes 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.

Retrieving data

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!

Clone this wiki locally