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 10 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.

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

Thanks!

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

2 answers

Log in to vote
1
Answered by 10 years ago

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

01function InTable(tab,val)
02    for _,n in pairs(tab) do
03        if n == val then
04            return true
05        end
06    end
07end
08 
09if contestants == 8 or contestants == 9 or contestants == 10 then
10    local RandomPlayer = contestants[math.random(1,#contestants)]
11    if not InTable(robber,RandomPlayer) then
12        table.insert(robber,RandomPlayer)
13    end
14end
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 — 10y
Ad
Log in to vote
0
Answered by 10 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 (:

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

Answer this question