Random Table Factory - Utility Function
hello.
i’ve just found an ideal (kind of) way to go through a table in random way, so it won’t use duplicated values with save of original lua’s syntax. i find this more flexible.
Source
function getIndexes(t)
local c = {}
for i, _ in t do
table.insert(c, i)
end
return c
end
-- so called `randomTableFactory`
return function(t: {any}, doRepeat: boolean?)
local c = getIndexes(t)
return coroutine.wrap(function()
while true do
if #c < 1 then
if doRepeat == true then
if #t < 1 then
break
end
c = getIndexes(t)
else
break
end
end
local n = math.random(1, #c)
local i = c[n]
table.remove(c, n)
local v = t[i]
coroutine.yield(i, v)
end
end)
end
Usage
you can use the iterator in whatever way possible, it’s kind of the reason i like them in general. let me just show.
In random order
for i, v in randomTableFactory(example) do
-- `randomTableIterator(example, false)` works as well
print(i, v)
end
Infinite use
for i, v in randomTableFactory(example) do
print(i, v)
end
Limited use
local iterator = randomTableFactory(example, true)
for _ = 1, #example * 1.5 do
local i, v = iterator()
print(i, v)
end
Call once
local i, v = randomTableFactory(example)()
print(i, v)
Conclusion
it really works as a proof of concept, but i’d like to use it myself honestly. the idea is really cool, even tho it’s more complicated than simple t[math.random(1, #t)]
. also i’m not too sure about optimization side.
i’m glad to share with it, i hope you’d find this helpful!