I have a table of items that can be earned from lootboxes but this is the code that picks a random item from a rareity table:
local RandomNumber = math.random(1,#LootboxModule.Regular[Common])
local ChosenItemRandom = LootboxModule.Regular[Common][RandomNumber]
PickedItem = ChosenItemRandom
To check if a player owns a item I just do:
CommonTable[player][1] -- this is the first common item in the table
How would I check if a player owns it before choosing a item? Cause i dont want any duplicates. If there is any where I could improve saving my items ^^ let me know
You can just use table.find. It will return nil if it doesn’t grab anything though so just make sure it did get something.
local FoundItem = table.find(CommonTable[player], ChosenRandomItem)
if FoundItem then
-- do something
end
This won’t work on clones of an object though, so if you are doing that then an alternative way is to do this:
--(only works on tables of instances)
local FoundItem
for _, Object in CommonTable[player] do
if Object.Name == PickedItem.Name then
FoundItem = Object
break
end
end
if FoundItem then
-- do something
end
this is helpful, but if I check that the player does own it how would I reroll it and make sure it doesnt roll the same item again just the player doesnt get a duplicated in their lootbox?
local SafetyBreak = 200
local BreakAmount = 0
if CommonTable[player] ~= LootboxModule.Regular[Common][RandomNumber] then
while table.find(CommonTable[player], ChosenRandomItem) do
if BreakAmount >= SafetyBreak then
warn("Auto break; does the player already own all the skins?")
break
end
BreakAmount += 1
RandomNumber = math.random(1,#LootboxModule.Regular[Common])
ChosenRandomItem = LootboxModule.Regular[Common][RandomNumber]
task.wait()
end
end
Just make sure that they dont own every skin or this will keep looping forever and probably crash. (I added a wait and a auto break as a last safety measure).
P.S. another way to get a random element from a table is like this:
local RandomElement = sometable[math.random(#sometable)]