Good day! I’m looking for any method to mitigate the invalid argument #2 to 'random' (interval is empty) in a math.random() function. What I’m trying to go for here is an item ‘deletion’ from its shelf. However, when the number of objects in the table reaches 1, which is the same as the minimum value of the range in math.random(), it returns the aforementioned error. What I want to happen is that, regardless of range, it will choose whatever is available from the range. Many thanks to anyone who can articulate and address my concern!
Code:
local clickParts = shelf.Click:GetDescendants() -- Shelf deletion by player
for i,v in ipairs(clickParts) do
if v:IsA("ClickDetector") then
v.MouseClick:connect(function()
local itemsTable = v.Parent.Parent.Parent:FindFirstChild("Items"):GetChildren()
local itemToBeDestroyed = itemsTable[math.random(1, #itemsTable)] -- ISSUE: Upper limit == Lower limit when 1 instance remains under itemsTable
itemToBeDestroyed:Destroy()
itemsLeft.Value -=1
print(#itemsTable)
end)
end
end```
Although, after a certain threshold has passed (the number of the item’s objects less than 1 or when it is empty) it returns an error, hence why I made this post.
It seems that it runs 2 times, then at the third time, the table is empty. (as you can see 2 prints in line 38, then it fails at the third repeat in the line before 38 - 35).
I suggest you check the items folder of the third click detector.
After a bit of documentation and trial and error, I’ve found out that indeed, the table would run even when it’s empty, expecting that there is one more object remaining. Forgive my jargon, but I think it “lags” behind the actual checking of the number of instances under the table, so I added a table.remove() function to help it keep track. Thank you everyone who gave their input! It really helps a lot.
for i,v in ipairs(clickParts) do
if v:IsA("ClickDetector") then
v.MouseClick:connect(function()
local itemsTable = v.Parent.Parent.Parent:FindFirstChild("Items"):GetChildren()
local itemToBeDestroyed = itemsTable[math.random(1, #itemsTable)] -- ISSUE: Upper limit == Lower limit when 1 instance remains under itemsTable
table.remove(itemsTable, 1)
itemToBeDestroyed:Destroy()
itemsLeft.Value -=1
print(#itemsTable)
end)
end
end```