Ok, so I'm coding a genetics system for [URL="http://www.facepunch.com/showthread.php?t=940273"]Colonies [/URL].
[code]
function ENT:RandomizeGeneticsOnSpawn()
Genetics.Slot1.name = headcrabgenes[math.random(1,#headcrabgenes)]
Genetics.Slot1.magn = math.random(0.1,2)
Genetics.Slot2.name = headcrabgenes[math.random(1,#headcrabgenes)]
Genetics.Slot2.magn = math.random(0.1,2)
Genetics.Slot3.name = headcrabgenes[math.random(1,#headcrabgenes)]
Genetics.Slot3.magn = math.random(0.1,2)
Genetics.Slot4.name = headcrabgenes[math.random(1,#headcrabgenes)]
Genetics.Slot4.magn = math.random(0.1,2)
Genetics.Slot5.name = headcrabgenes[math.random(1,#headcrabgenes)]
Genetics.Slot5.magn = math.random(0.1,2)
end
[/code]
Problem is, I need to make sure none of genes are the same. That is, Genetics.Slot#.name != any others.
Is there any code-efficient way of doing this? I really don't want to do prohibitively large amounts of code for each slot.
You can make a function to return a function that removes and returns a random variable from a copy of the table so that it can not be returned again.
[lua]function table.Random2(tab)
local t = table.Copy(tab)
return function()
if #t == 0 then
return
end
return table.remove(t, math.random(1, #t))
end
end[/lua]
Example:
[lua]function ENT:RandomizeGeneticsOnSpawn()
local r = table.Random2(headcrabgenes)
Genetics.Slot1.name = r()
Genetics.Slot1.magn = math.random(0.1,2)
Genetics.Slot2.name = r()
Genetics.Slot2.magn = math.random(0.1,2)
Genetics.Slot3.name = r()
Genetics.Slot3.magn = math.random(0.1,2)
Genetics.Slot4.name = r()
Genetics.Slot4.magn = math.random(0.1,2)
Genetics.Slot5.name = r()
Genetics.Slot5.magn = math.random(0.1,2)
end[/lua]
[editline]12:14PM[/editline]
Each slot would then get a random, but different name from the table.
-snip snap-
[QUOTE=commander204;22192765]The Idea is good only the code will not work as it will copy the table everytime you use it.[/QUOTE]
No it won't. Look at the code again.
[editline]02:41PM[/editline]
It works, I have tested it. I wouldn't have posted it if I wasn't sure that it works.
[editline]02:43PM[/editline]
Also, read through the example. I only call table.Random2 once.
Ah I see now, yeah my bad :/
Sorry, you need to Log In to post a reply to this thread.