lloyAlloy on GitHub
Set
Docs

Set

Updated
Set<T>
import { Set } from "@alloy/std/collections"

local seen = $set[1, 2, 3]
local s: Set<string> = new Set()
if s:add("a"):has("a") then end

A set with methods, from the std. Any value that is not nil is a member. new Set() is empty, Set.from(t) takes an array's items, and $set[a, b] is the literal. for value in s walks the members, in no set order.

Statics

Set.new

Set.new<T>(items: { T }?): Set<T>

An empty set, or with items the set Set.from(items) gives. The annotation on the binding fixes T of an empty set.

import { Set } from "@alloy/std/collections"

local seen: Set<string> = new Set()
seen:add("a")

Set.from

Set.from<T>(items: { T }): Set<T>

A new set with the items of an array. A repeated item joins once.

import { Set } from "@alloy/std/collections"

local seen = Set.from({ 1, 2, 2, 3 })
print(seen:len())

Methods

Set:add

Set:add(value: T): Set<T>

Adds value and returns the set, so calls chain. Adding a member again changes nothing.

import { Set } from "@alloy/std/collections"

local seen: Set<string> = new Set()
if seen:add("a"):has("a") then
    print("added")
end

Set:has

Set:has(value: T): boolean

Whether value is a member.

local seen = $set[1, 2, 3]
print(seen:has(2))

Set:remove

Set:remove(value: T): boolean

Removes value and says whether it was there.

local seen = $set[1, 2]
print(seen:remove(1))

Set:len

Set:len(): number

The number of members. The set counts as members come and go.

local seen = $set[1, 2, 3]
print(seen:len())

Set:union

Set:union(other: Set<T>): Set<T>

A new set of the members of both. Neither input changes.

local a = $set[1, 2]
local b = $set[2, 3]
print(a:union(b):len())

Set:intersection

Set:intersection(other: Set<T>): Set<T>

A new set of the members that both hold.

local a = $set[1, 2]
local b = $set[2, 3]
print(a:intersection(b):len())

Set:difference

Set:difference(other: Set<T>): Set<T>

A new set of this set's members that other does not hold.

local a = $set[1, 2]
local b = $set[2, 3]
print(a:difference(b):len())

Set:clear

Set:clear()

Removes every member and sets the count to zero. The set itself stays, so every reference to it sees the empty set.

local seen = $set[1, 2, 3]
seen:clear()
print(seen:len())

Set:to_array

Set:to_array(): T[]

The members as an array, in no set order.

local seen = $set[1, 2, 3]
print(seen:to_array():len())

Set:to_table

Set:to_table(): { [T]: boolean }

The set's own table, not a copy: each member is a key with the value true. A write through it changes the set and skips the count, so use add when len must stay true.

local seen = $set[1, 2]
local t = seen:to_table()
print(t[1])