Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I use a table to randomize teleports CFrame?

I was testing a teleport where when you touched a part outside of the Lobby, it would teleport you back into the lobby. There was this error, here is my code and the error: Error:

22:25:09.867 - Workspace.Workspace.Sea.Script:12: bad argument #2 to 'random' (interval is empty)
22:25:09.868 - Stack Begin
22:25:09.869 - Script 'Workspace.Sea.Script', Line 12
22:25:09.869 - Stack End

Code:

script.Parent.Touched:Connect(function(hit)
	local Humanoid = hit:FindFirstChild("Humanoid")
	if Humanoid ~= nil then
		wait()
	else
		print("Humanoid touched "..script.Parent.Name..".")
		local rootPart = hit:FindFirstChild("HumanoidRootPart")
		local spawns = {
			spawn1 = game.Workspace.lobbySpawn1.CFrame,
			spawn2 = game.Workspace.lobbySpawn2.CFrame
			}
		rootPart.CFrame = spawns[math.random(1,#spawns)]
		local Success = "successTeleport"
	end
end)

Thank you, I hope to recieve an answer.

1 comment

0

By the way, the local Success = "successTeleport" code is something i'm doing along side the script.

1 answer

✓ Accepted answer

you are using the length operator '#' to get the length of the table, hovever, this only works on tables that use regular number keys (1,2,3,4,etc) not string keys as shown in the example ("spawn1","spawn2",etc), so the '#' returns 0 because no number keyed items were found, this caused the maximum parameter for math.random() to be less than the minimum (1=1,#spawns=0) so you got an error relating to math.random

the solutions:

solution 1:

use a table that uses number keys

local spawns = {
            game.Workspace.lobbySpawn1.CFrame,
            game.Workspace.lobbySpawn2.CFrame
            }

solution 2:

us a function to get its length including string keys

function GetLength(t)
	local final = 0
	for _,v in pairs(t) do final = final + 1 end
	return final
end
rootPart.CFrame = spawns[math.random(1,GetLength(spawns))]

2 comments

0

I am so confused. What do you even mean by "regular number keys"? How is there a difference?

0

Oh I see now, apologies for that comment.

This discussion is preserved as it was. New answers, comments, and votes are closed.