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

How do I make math.random print a string?

Asked by 3 years ago

I want to print a random food from a table I made but it only prints numbers what do I do?

2 answers

Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

I think this method only works on arrays.

table[math.random(1,#table)]

--[[
So if the length of your table is 5 it will look like this
table[math.random(1, 5)] and if the result of the math.random is 3 then it will look like this
table[3] this means will pick the 3rd index.
]]

So table is the variable name of your table and picking a random index. #table means the length of a table meaning the number of values in your table.

Ad
Log in to vote
0
Answered by 3 years ago

Hi I may have an answer for your question.

First your create a table of foods:

local food = {'cabbage', 'Sausage', 'MyMum'}

then, say there are SO many foods in your list you literally will be dead if you count them. you should use # to find how many are in the table:

local tablenum = #food

then you need to use math.random() to get a random number!

local randomnum = math.random(1,tablenum)

now you know which number food to pick! you just need to apply this by finding the value of that number in the table!

tableval = food[randomnum]

Now you have chosen your food! You just need to print this!

print(tableval)

Congrats You got it!

Here's the full script:

local food = {'cabbage', 'Sausage', 'MyMum'}
local tablenum = #food
local randomnum = math.random(1,tablenum)
tableval = food[randomnum]
print(tableval)

Hope this helped!

Any Questions? Just ask!

Answer this question