Created
January 16, 2024 20:55
-
-
Save Fizzyhex/a59a7e9c369e6a9d5ac912bed6723844 to your computer and use it in GitHub Desktop.
Luau Sample Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--!strict | |
-- src: https://gist.github.com/Uradamus/10323382 | |
local function shuffle<T>(tbl: { T }): { T } | |
tbl = table.clone(tbl) | |
for i = #tbl, 2, -1 do | |
local j = math.random(i) | |
tbl[i], tbl[j] = tbl[j], tbl[i] | |
end | |
return tbl | |
end | |
local function sample<T>(array: { T }, pool: { T }): T | |
if #pool == 0 then | |
return sample(array, shuffle(array)) | |
end | |
return table.remove(pool) :: T | |
end | |
local names = {"Foo", "Bar", "Baz", "Qux"} | |
local pool = {} | |
for _ = 1, 20 do | |
print(sample(names, pool)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment