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:
1 | 22 : 25 : 09.867 - Workspace.Workspace.Sea.Script: 12 : bad argument # 2 to 'random' (interval is empty) |
2 | 22 : 25 : 09.868 - Stack Begin |
3 | 22 : 25 : 09.869 - Script 'Workspace.Sea.Script' , Line 12 |
4 | 22 : 25 : 09.869 - Stack End |
Code:
01 | script.Parent.Touched:Connect( function (hit) |
02 | local Humanoid = hit:FindFirstChild( "Humanoid" ) |
03 | if Humanoid ~ = nil then |
04 | wait() |
05 | else |
06 | print ( "Humanoid touched " ..script.Parent.Name.. "." ) |
07 | local rootPart = hit:FindFirstChild( "HumanoidRootPart" ) |
08 | local spawns = { |
09 | spawn 1 = game.Workspace.lobbySpawn 1. CFrame, |
10 | spawn 2 = game.Workspace.lobbySpawn 2. CFrame |
11 | } |
12 | rootPart.CFrame = spawns [ math.random( 1 ,#spawns) ] |
13 | local Success = "successTeleport" |
14 | end |
15 | end ) |
Thank you, I hope to recieve an 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
1 | local spawns = { |
2 | game.Workspace.lobbySpawn 1. CFrame, |
3 | game.Workspace.lobbySpawn 2. CFrame |
4 | } |
solution 2:
us a function to get its length including string keys
1 | function GetLength(t) |
2 | local final = 0 |
3 | for _,v in pairs (t) do final = final + 1 end |
4 | return final |
5 | end |
1 | rootPart.CFrame = spawns [ math.random( 1 ,GetLength(spawns)) ] |