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

How can I insert only two items into a table?

Asked by 9 years ago

I want to insert two random players into a table, and check if they are in the table before they are put in, so that noone is put in the table twice. I have tried making this script, but I have no idea if it works.

if #contestants == 8 or #contestants == 9 or #contestants == 10 then
    for _, randomplayers in pairs(2 * math.random(1, #contestants)) do
        if randomplayers and randomplayers.Health > 0 then
            table.insert(robber, randomplayers)
        end
    end

Thanks!

0
In your for loop you are trying to loop through a number? NotsoPenguin 705 — 9y
0
It is supposed to pick a contestant. I figured out that the loopo above wasn't going to work. SonioSony 53 — 9y

2 answers

Log in to vote
1
Answered by 9 years ago

It is best to create a function to see if a value is in the table.

function InTable(tab,val)
    for _,n in pairs(tab) do
        if n == val then
            return true
        end
    end
end

if contestants == 8 or contestants == 9 or contestants == 10 then
    local RandomPlayer = contestants[math.random(1,#contestants)]
    if not InTable(robber,RandomPlayer) then
        table.insert(robber,RandomPlayer)
    end
end
0
Thanks! But how can I put more than one contestant in the table? Say I only want have two players there, or even 4. SonioSony 53 — 9y
Ad
Log in to vote
0
Answered by 9 years ago

I believe I have solved it! If anyone else is wondering about the same thing, here is the script I made. Not sure if it works yet but I havee my fingers crossed (:

if #contestants == 8 or #contestants == 9 or #contestants == 10 then
    local randomplayer1 = contestants[math.random(1, #contestants)]
    while true do
        local randomplayer2 = contestants[math.random(1, #contestants)]
        if randomplayer2 ~= randomplayer1 then
            table.insert(robber, randomplayer1, randomplayer2)
            break
        end
    end

Answer this question