Shorten math.random() checks

I want to shorten math.random without using a lot of if / then statements but I simply cant

this is the a part of the code:

if random == 1 then
	waiting(id1)
elseif random == 2 then
	waiting(id2)
elseif random == 3 then
	waiting(id3)
elseif random == 4 then
	waiting(id4)
elseif random == 5 then
	waiting(id5)
elseif random == 6 then
	waiting(id6)
elseif random == 7 then
	waiting(id7)
elseif random == 8 then
	waiting(id8)
elseif random == 9 then
	waiting(id9)
elseif random == 10 then
	waiting(id10)
elseif random == 11 then
	waiting(id11)
end

I want it to be like this:

waiting(id .. random)

(random is math.random(1, 11) and the ids are image ids)

I would recommend you to use a Switch operation instead but I’m not really sure there is any Switch operation…

1 Like
local tableofwaiting = {} -- add your waitings in order
local randomget = tableofwaiting[random]
1 Like

what is the value of id1, id2…

right now
and are they all variables

I do not fully understand the your question but here is the my solution for that:

You can use a table to store the ids and then use the random number as an index into the table.

local ids = {id1, id2, id3 ... id11}
waiting(ids[random])
1 Like
"http://www.roblox.com/asset/?id=9881423508"
"http://www.roblox.com/asset/?id=9882198649"
--and so on

yes, they all are variables

Make sure you don’t name the variable “random” because its already a used word, name it randomNum
2 different methods:

  1. Make a table with the ids:
local ids = {
	id1,
	id2,
	id3,
	...
}

And then you can get the id like this: ids[randomNum]

  1. Save the images as decals, and put them inside a group or folder, and name every decal like “Decal1” or “Decal2” or so on:
local ids = --The folder that the decals are in
local id = ids:FindFirstChild("Decal"..randomNum)
1 Like

I like switch(), it make much more readable code but they don’t exist in Lua.

This is what I came up with. Basically, instead of your program making a random number and then going through a ton of if statements till it finds a match, the following script allows your program to create the random number, and then automatically match that number with the index of the table.

For example, the tables has, " A string " for the 1st index. The 1st index is whatever is wrote first, the second is right after first, on & on.

You will be able to put your ID’s in place of the index numbers, so {111,222,333,444}, and whenever you run the program your random number will be matched with the index number to get you the ID you wanted for that number.

In this example, I used the print function, but if you use this same exact outline, then it will work with any other statement.

local testArray = {"A string", "3.14159", "Hello", "New string"} 
local random = math.random(1,4) 

print(testArray[random])

Hope this helps! :slight_smile:

Show me the full script I can only do so much without it

idk how you call random and other values?


so far