Issue with choosing a random value from a table

Having an issue where the length of a table is appearing as 0 even though a printout of the table shows there is at least 1 item in it.

The code I am using is as follows, I am attempting to filter an object for a specific part, then add that to a table and return a random value from that table.

The error I am receiving is from the Math.Random part which is as follows:
invalid argument #2 to 'random' (interval is empty)

function ChooseRandomDoor(model)
	local SelectedDoor
	
	local ListOfDoors = {}
	
	for i, v in pairs(model:GetDescendants()) do
		if v.Name == "Attachment_Exit" then
			ListOfDoors[i] = v
			print(ListOfDoors)
			print(#ListOfDoors)
			print(ListOfDoors)
			SelectedDoor = ListOfDoors[math.random(1, #ListOfDoors)]
		end
	end
	return SelectedDoor
end

Code examples would be appreciated :slight_smile: ( Sorry if this topic already exists, couldnt find anything on my specifc issue.

From what I can see, you’re trying to select a random door from all of the descendants in a model. If this is the case, there are a couple of things you should try.

The first issue I see is that you’re using the direct index from the for-loop, however the i variable won’t necessarily be in a sequential order since you are skipping all of the parts that are not named Attachment_Exit. You can fix this by utilising the table.insert() lua method which I’ve shown in the code sample below.

Additionally, you should only be selecting a random door once all of the doors have been added into the array. Here is a snippet of code which should work:

function ChooseRandomDoor(model)
	local SelectedDoor
	
	local ListOfDoors = {}
	
	-- the 'i' variable is replaced with an underscore to show that it's unused.
	for _, v in pairs(model:GetDescendants()) do
		if v.Name == "Attachment_Exit" then

			-- Insert the door in the next position in the table.
			table.insert(ListOfDoors, v)

			--[[
			print(ListOfDoors)
			print(#ListOfDoors)
			print(ListOfDoors)
			]]
		end
	end

	-- Wait until all the doors have been added (after the for-loop).
	SelectedDoor = ListOfDoors[math.random(1, #ListOfDoors)]

	return SelectedDoor
end

Hopefully this helps!

1 Like

This appears to be working, thank you.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.