Is there a such thing as table.Randomize()?

Hello, I am looking for a function that will scramble a table, not have any double rows, and have the same values as it did before but just in a different order. Is there a function that can do this? Or is there a way I can do it?

Do the key values have to stay the same, or does it not matter?

Key value doesn’t matter.

Oh good.

Simply make a for loop that randomly picks two of the key values in the table, and swaps the value. Just loop it like k*4 times and that should randomize it well enough.

Actually, now that I think about it, it don’t think this would even affect key value anyway.



	for k,v in pairs(WeaponsRotation) do
		WeaponsRotation[k] = WeaponsRotation[k*4]
	end


What if WeaponRotation doesn’t have a row that is, let’s say k is 10, what if it doesn’t have a row 40?

Assuming your table is numeric ( and flat ), something like this would be ideal:


function table.randomize( t )
	local out = { }
	
	while #t > 0 do
		table.insert( out, table.remove( t, math.random( #t ) ) )
	end
	
	return out
end


local data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }

data = table.randomize( data )

for k, v in pairs( data ) do
	print( k, v )
end


1	3
2	6
3	1
4	12
5	10
6	5
7	13
8	15
9	14
10	7
11	9
12	11
13	2
14	4
15	8

No, like

(I haven’t done lua in a while, so forgive me.)

[LUA]
for i=0, 10 do

random1 = math.random(0,10)
random2 = math.random(0,10)

local value1 = table[random2]

table[random2] = table[random1]

table[random1] = value1

end
[/LUA]

I don’t know, hopefully that’ll give you a general idea.