So I’m making a game kinda like SCP 3008. And I’m trying to make a rarity system on the different rooms. Example: Bedroom’s chance of spawning = 5% and Cafeteria’s chance of spawning = 1%.
I have tried to make this using a Table. The given numbers are the chance they have to spawn.
function GetRandomItem()
local Sum = 0
for RoomName,Chance in pairs(RoomsChances) do
Sum += Chance
end
local RandomNumber = math.random(Sum)
for RoomName,Chance in pairs(RoomsChances) do
if RandomNumber <- Chance then
return RoomName -- Error from here
else
RandomNumber -= Chance
end
end
end
function GetRandomItem()
local Sum = 0
for RoomName,Chance in pairs(RoomsChances) do
Sum += Chance
end
local RandomNumber = math.random(Sum)
for RoomName,Chance in pairs(RoomsChances) do
if RandomNumber <= Chance then
return RoomName -- Error from here
else
RandomNumber -= Chance
end
end
end
It is also worth noting that since the values don’t change you only have to calculate sum once.
local Sum = 0
for RoomName,Chance in pairs(RoomsChances) do
Sum += Chance
end
function GetRandomItem()
local RandomNumber = math.random(Sum)
for RoomName,Chance in pairs(RoomsChances) do
if RandomNumber <= Chance then
return RoomName -- Error from here
else
RandomNumber -= Chance
end
end
end
But you probably won’t actually see the performance improvement with how slight it is. Making it practically useless.