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

How do I get two random values from a table?

Asked by 5 years ago
PlayersInServer={}
math.randomseed(tick())
            for i=1,2 do
                local value=math.random(1,#PlayersInServer)
                local picked=PlayersInServer[value]
                print(picked)
            end

This will usually just pick two of the same people, how would I get two random values?

1
Make another table and put the first person in that table. Then check if the second value is the same person, and if it is then end the loop. DeceptiveCaster 3761 — 5y

2 answers

Log in to vote
0
Answered by
Lodok3 18
5 years ago
local PlayersInServer = {}
local ChosenPlayers = {}
for i=1,2 do
    if i == 1 then
    local RandomValue = math.random(1,#PlayersInServer)
    local ChosenPlayer = PlayersInServer[RandomValue]
    table.insert(ChosenPlayers,ChosenPlayer)
    end
    if i == 2 then
        local RandomValue = math.random(1,#PlayersInServer-1)
        local PlayersInServerCopy = PlayersInServer
        table.remove(PlayersInServerCopy,ChosenPlayers[1])
        local ChosenPlayer = PlayersInServerCopy[RandomValue]
        table.insert(ChosenPlayers,ChosenPlayer)
    end

    RandomValue = math.random(1,#PlayersInServer)
end
for i=1,2 do
    print(ChosenPlayers[i])
end

This should work as a script for what you are doing. So on lines 5 to 7, it will generate a random value, choose a player then add it to the ChosenPlayers table. On lines 10 to 14, the script will generate a random value for the PlayersInServer table, minus one (because we have already used it in the ChosenPlayers table), it will then make a duplicate of PlayersInServer named PlayersInServerCopy, remove the already chosen value from PlayersInServerCopy and add the make a new ChosenPlayer and add it.

Ad
Log in to vote
0
Answered by
Thetacah 712 Moderation Voter
5 years ago

Something that may seem a little more simple. Note that this method is not ideal, as it will only works for finding two random players. Otherwise you'd want to use a Table to accomplish this.

local PlayersInServer = {}
math.randomseed(tick())

local previous;

for i=1,2 do
    repeat
        local value =math.random(1,#PlayersInServer)
            picked = PlayersInServer[value]
    until previous ~= picked

    previous = picked
    print(picked)
end

Answer this question