-- your list of items, I tend to have these in a seperate module
local items = {
{Name = "Iron Sword"},
{Name = "Iron"},
{Name = "Gold"}
}
--[[
a loot table, it's wise to keep these seperate from your item list as it allows you to make
multiple loot tables
needs to be linear, greatest to least, and remember it's based on weight not percentages
--]]
local lootTable = {
{Item = items[2], Weight = 95}, -- each one of these is an entry
{Item = items[3], Weight = 75},
{Item = items[1], Weight = 1}
}
-- used in weight random number generation
local function returnSumOfWeight(lootTable)
local sum = 0
for _, entry in ipairs(lootTable) do
sum = sum + entry.Weight
end
return sum
end
-- returns a random item from given lootTable
local function getRandomItem(lootTable)
-- returns a random number based on total weight of given lootTable
local randomNumber = math.random(returnSumOfWeight(lootTable))
for _, entry in ipairs(lootTable) do
if randomNumber <= entry.Weight then
return entry.Item
else
randomNumber = randomNumber - entry.Weight
end
end
end
-- just for testing, mess around with it how you like
for i = 1, 1000 do
local item = getRandomItem(lootTable)
print(item.Name)
end
To embed this project on your website, copy the following code and paste it into your website's HTML: