This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
jtdavis99's profile picture

Random Choice

Started by jtdavis99, 02 March 2012 - 07:18 PM
jtdavis99 #1
Posted 02 March 2012 - 08:18 PM
I was wondering if there was a way to randomly pick one thing from a bucket of others? So, like random("red, blue, green, purple") and it'd pick one out of that, as an example.
Liraal #2
Posted 02 March 2012 - 08:21 PM
math.random(min, max)
Advert #3
Posted 02 March 2012 - 08:22 PM
Yes, there is. You'll want to use a table though:


local items = {"apple", "pie", "banana", "orange"}


print(items[math.random(1, #items)]) -- Pick a random item

-- Do it again a few times:
for i = 1, 10 do
 print(items[math.random(1, #items)])
end

The function you're looking for is math.random(min, max), and you'll want to use it in addition to a table, and it's # operator (returns the total number of items in it).

Note that the # operator will only return the count of items starting from 1, until it doesn't exist:


local items = {"apple", "pie", 4 = "banana"}

print(#items) -- This will print 2, since items[3] is nil.
jtdavis99 #4
Posted 02 March 2012 - 08:22 PM
math.random(min, max)
Is there a way to do it with words?
ChaosBeing #5
Posted 03 March 2012 - 06:58 AM
That's what the code above does. See this line of Advert's example?

local items = {"apple", "pie", "banana", "orange"}

That's creating a table (think of table's as a kind of list) of the words "apple", "pie", "banana", and "orange".

Then this,

print(items[math.random(1, #items)]) -- Pick a random item

Prints one of them out at random. He uses math.random to get a random number between 1 and the number of items in the table, and then uses that number to access that word. Using the above example again, there's four words for it to choose from, so random will select any number from 1 to 4.

Now, see how the math.random is inside of square brackets? These square brackets tell the table 'items' which word you're looking for. For example, if math.random returned 3, that line would print out "banana". Just the same as how if math.random return 2, it'd print out "pie".
Glaze #6
Posted 29 September 2013 - 02:21 PM
ChaosBeing, I want to implement this in a script for a survival map so it would randomly pick an option and my script is for wired networks

My script
peripheral.wrap("computer_0")
peripheral.wrap("monitor_3")
peripheral.call("bottom", "callRemote", "monitor_3", "write", " Hack Succesfull")
sleep(15)
local items = {"1", "2", "3"}
8 = items[math.random(1, #items)] – Random :D/>
if 8 == 1 then do
local function OS()
shell.run("startup")
end
else
2 = local function OS2()
shell.run("server.terminated")
end
end
parallel.waitForAny( OS, OS2 )
Everything works exept the random chooser
immibis #7
Posted 29 September 2013 - 08:13 PM
You can't have a variable called 8.
Glaze #8
Posted 06 October 2013 - 11:20 AM
You can't have a variable called 8.
F i derped sorry