Make my script more efficient

local FirePicks = 0
local HowManyFires = 2
local RainPicks = 0
local HowManyRains = 2

function GenerateDigit1()
	local RandomRange = math.random(0, 9) -- 0 through 9
	local RandomImage = math.random(1, 2) -- # of Images
	RandomDigit1.Value = tostring(RandomRange)
	if RandomImage == 1 and RainPicks <= HowManyRains then -- Rain
		RainPicks = RainPicks + 1
		Image1.Decal.Texture = RainDropID.Value
		CombinationItems.Digit1.Value = RandomDigit1.Value
		ActualRain.Parent = CombinationItems
	end
	if RandomImage == 2 and FirePicks <= HowManyFires then -- Fire
		FirePicks = FirePicks + 1
		Image1.Decal.Texture = FireID.Value
		CombinationItems.Digit1.Value = RandomDigit1.Value
		ActualFire.Parent = CombinationItems
	end
end

My combination lock is completely randomized, and it has a total of 7 digits, ranging from 0-9.

(this function is just to randomize 1 digit)

I want it to have alteast 10 different if statements, and 7 GenerateDigit() functions, so how do I make this one function more efficient?

My goal is so that I don’t need to copy and paste the if statesments 10 times, and change each one, and make 7 functions with 10 if statements within them.

You can use for loops

1 Like

How would I do that? Could you maybe show an example?

I’m not good with for loops, if you give me a minute I can give you an example

1 Like

Yeah, take your time! I’ll just be browsing the dev forum.

You can do something like this

local RandomizedTable = {
	Rain = {1, 0, 2, RainDropID, ActualRain}; --RandomImage, Pick, HowMany, ImageID, ObjectName
	Fire = {2, 0, 2, FireID, ActualFire}
}

function GenerateDigit1()
	local RandomRange = math.random(0, 9)
	local RandomImage = math.random(1, 2)

	RandomDigit1.Value = tostring(RandomRange)
	
	for Key, Value in pairs(RandomizedTable)do
		if Key[1] == RandomImage and Key[2] <= Key[3] then
			Key[2] += 1
			Image1.Decal.Texture = Key[4]
			CombinationItems.Digit1.Value = RandomDigit1.Value
			Key[5].Parent = CombinationItems --or maybe (Thing:FindFirstChild(Key[5]).Parent = CombinationItems)
		end
	end
end
1 Like

Oh, @Crygen54 was able to do it, I don’t think you need my help for this

1 Like

I think this would work perfectly, but it needs a few changes that I don’t quite know how to do myself. RandomImage is there in my first version of my script, and that is because that would determine if it is Rain, or Fire, but since the in pairs already randomizes that, I don’t think RandomImage is necessary.

How do you change this?

Actually don’t listen to me, the problem is not the RandomImage, because I didn’t realize what it did, it’s because the Decal didn’t load and I thought it was because of that, thank you and it worked perfectly!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.