Attempt to get length of a Instance value

function mainModule.GenerateStop()
	for i, v in pairs(RSStopStorage:GetChildren()) do
		local randomStop = v[math.random(1, #v)] -- Error Here
		
		randomStop.Parent = WSStopStorage
		BE.NewStop:Fire()
		
		mainModule.TweenGlass(1, MainSubway.LeftDoor.Glass, Color3.fromRGB(152, 194, 219), 0.75)
		mainModule.TweenGlass(1, MainSubway.RightDoor.Glass, Color3.fromRGB(152, 194, 219), 0.75)
		task.wait(1)
		mainModule.TweenDoors(1, MainSubway.LeftDoorOutDestination, MainSubway.LeftDoor.Door)
		mainModule.TweenDoors(1, MainSubway.RightDoorOutDestination, MainSubway.RightDoor.Door)
		
		Values.Stops.Value += 1
		Values.AtStop.Value = true
	end
end

When I try and localize randomStop in output it always says: "attempt to get length of a Instance value".

(I also just tried putting local randomStop = math.random(1, #v) but it still says the same thing in output.)

I assume it’s because the things inside RSStopStorage are parts, and not numbers.

Hope this was enough information!
Any help is appreciated!

You’re trying to use #v, which is the length operator, on an instance value. The # operator only works on tables that have sequential integer keys, which is why you’re getting the “attempt to get length of Instance value” error message.

replace #v with table.getn(v) or table.maxn(v). Both table.getn() and table.maxn() return the size of the table (the number of elements in a sequence table), which should work for your use case.

So your code should look something like:

local randomStop = v[math.random(1, table.getn(v))]

or

local randomStop = v[math.random(1, table.maxn(v))]
1 Like

Now it says: "(table expected, got Instance)"

Here is a screen shot of my explorer:
workspace screenshot

I’m not sure how to fix this problem.

Nevermind, I got the solution.

I just got rid of the for loop and replaced it with

local stopChildren = RSStopStorage:GetChildren()
local randomStop = stopChildren[math.random(1, #stopChildren)]

Thank you for your help though!

No problem! Sorry I didn’t see the message sooner.

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