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
4 years ago
Edited 4 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:

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.

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

1 answer

Log in to vote
1
Answered by 4 years ago
Edited 4 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

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))]
0
I am so confused. What do you even mean by "regular number keys"? How is there a difference? harstud 218 — 4y
0
Oh I see now, apologies for that comment. harstud 218 — 4y
Ad

Answer this question