Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I use a table to randomize teleports CFrame?

Asked by
harstud 218 Moderation Voter
5 years ago
Edited 5 years ago

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:

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

Code:

01script.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            spawn1 = game.Workspace.lobbySpawn1.CFrame,
10            spawn2 = game.Workspace.lobbySpawn2.CFrame
11            }
12        rootPart.CFrame = spawns[math.random(1,#spawns)]
13        local Success = "successTeleport"
14    end
15end)

Thank you, I hope to recieve an answer.

0
By the way, the local Success = "successTeleport" code is something i'm doing along side the script. harstud 218 — 5y

1 answer

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

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

1local spawns = {
2            game.Workspace.lobbySpawn1.CFrame,
3            game.Workspace.lobbySpawn2.CFrame
4            }

solution 2:

us a function to get its length including string keys

1function GetLength(t)
2    local final = 0
3    for _,v in pairs(t) do final = final + 1 end
4    return final
5end
1rootPart.CFrame = spawns[math.random(1,GetLength(spawns))]
0
I am so confused. What do you even mean by "regular number keys"? How is there a difference? harstud 218 — 5y
0
Oh I see now, apologies for that comment. harstud 218 — 5y
Ad

Answer this question