Jump to content

code reduction


fairyoggy

Recommended Posts

How can I shorten this code so as not to write many lines?

local ex1 = math.random(1,10)
local ex2 = math.random(1,10)
local ex3 = math.random(1,10)
local ex4 = math.random(1,10)
local ex5 = math.random(1,10)
local ex6 = math.random(1,10)
local ex7 = math.random(1,10)
local ex8 = math.random(1,10)
local ex9 = math.random(1,10)
local ex10 = math.random(1,10)

I want to shorten the code so as not to write a lot of lines, but at the same time so that each variable has a different random number. I'm sure it's easy, but I still don't understand how?

Link to comment
  • Moderators
29 minutes ago, fairyoggy said:

but at the same time so that each variable has a different random number

Requiring a loop and a table.

function generateRandomNumbers (count, maxSize)
	local randomNumbers = {}
	for i=1, count do
		randomNumbers[#randomNumbers + 1] = math.random(maxSize)
	end
	return randomNumbers
end

 

local randomNumbers = generateRandomNumbers(30, 10) -- Generate 30 random numbers. With a max value of 10

print(1, randomNumbers[1]) -- 1 <random number>

print(5, randomNumbers[5]) -- 5 <random number>

print(10, randomNumbers[10]) -- 10 <random number>

print(30, randomNumbers[30]) -- 30 <random number>

 

  • Like 1
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...