Random Table Factory - Utility Function

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!

1 Like
local t = {}
Random.new():Shuffle(t)

for i,v in t do
print(i, v)
end

this also works, yet simpler than mine utility function.

i see it as a part i can replace with, but the utility function won’t be the same as i intended it to be for my purposes or as it already is.
like there are cases when you’d need to keep the original table unchanged (that’s why i create a new table with indexes) or save orginal’s table indexes for smth in the future.

thank you anyway. i never checked Random’s methods, unfortunately as i see