I have been trying to come up with a way to do this, but I can’t think of anything. I am looking to make a vending machine that gives player’s specific items. (I already have it made). I am trying to make a dictionary which can declaire the item, as well as the percent chance to get it. How can I code it so that it will take that percentage and use it to determine what item is selected.
Wrote a little function that could help you out. Let me know if you’ve got any questions
--Table of items and their probabilities
local itemProbabilities = {
firstItem = 50,
secondItem = 10,
thirdItem = 20,
fourthItem = 20,
}
--Vending machine function, which passes through the table as a parameter
local function vendingMachine(items)
local randomNumber = math.random(1, 100) --Generating random number from 1-100
local correspondingProbability = 0
--What this does is it adds up all the probabilities, then when it finds the range in between the probability in the table,
-- it returns the corresponding key.
for key, probability in pairs(items) do
local previousProbability = correspondingProbability
correspondingProbability += probability
if previousProbability < randomNumber and randomNumber <= correspondingProbability then
return key
end
end
end
local choosenValue = vendingMachine(itemProbabilities)
print(choosenValue) -- prints your key value from the table