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

how to pick all numbers in the range from x to y?

Asked by 3 years ago

this is probably a stupid question, but i got random number and now i need to get all numbers in the range from 1 to 3 and 4 to 7. how do i do this? example:

local numb = math.random(1,7)
if numb == 1,3 then  --incorrect line
    print("1")
elseif numb = 4,7 then --incorrect line
    print("2")

etc.

2 answers

Log in to vote
2
Answered by 3 years ago

You could use the or operator like so:

local numb = math.random(1,7)

if numb == 1 or numb == 2 or numb == 3 then -- if it is 1,2 or 3

    print("it is a number between 1 and 3 - "..numb)

elseif numb == 4 or numb == 5 or numb == 6 or numb == 7 then -- if it is 4,5,6 or 7

    print("it is a number between 4 and 7 - "..numb)

end

Or you could use a table, and the table.find function (recommended):

local numbTable = {

    oneToThree = {1,2,3},
    fourToSeven = {4,5,6,7}

}

local numb = math.random(1,7)

if table.find(numbTable["oneToThree"],numb) then

    print("it is is a number between 1 and 3 - "..numb)

elseif table.find(numbTable["fourToSeven"],numb) then

    print("it is is a number between 4 and 7 - "..numb)

end

Hope this helped!

Ad
Log in to vote
1
Answered by
ben0h555 417 Moderation Voter
3 years ago

Simple! Use inequalities! (i.e. less than, greater than, less or equal to, etc.)

Heres an example of your code using this!

local numb = math.random(1,7)
if numb >= 1 and numb <= 3 then 
    print("1")
elseif numb >= 4 and numb <= 7 then
    print("2")
end
0
I do like this answer. 8oe 115 — 3y

Answer this question