Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I make my script a bit less repetitive?

Hello, so I'm tired of adding a bunch of if/elseif statements to my scripts where I have to check if the thing that got selected in a table matches to what I inputted, and I just think theres a better, and neater way to do this stuff.

Here's an example:

local foods = {"Apple", "Banana", "Grapes", "Carrot"}

function getColour(food)
   if food == foods[1] then --Beyond here is a bit repetitive, how can I change this?
      print("Red")
   elseif food == foods[2] then
      print("Yellow")
   elseif food == foods[3] then
      print("Purple")
   elseif food == foods[4] then
      print("Orange")
   end
end

getColour("Banana")

1 answer

✓ Accepted answer

Here is my approach, using the food names as keys and their respective colours as values.

local FoodColour = {
	Apple = "Red",
	Banana = "Yellow",
	Grapes = "Purple",
	Carrot = "Orange"
}

local function getColour(food)
	local colour = FoodColour[food] or "Unknown"

	print("The colour of " .. food .. " is " .. colour)
end

getColour("Grapes")  -->The colour of Grapes is Purple
getColour("Bacon")  -->The colour of Bacon is Unknown

2 comments

1

I have no idea why this was downvoted. Whoever did so is clearly ignorant to efficient practices. I apologize, I'll accept this for you!

0

Nice job, this script is way better than anything that could make.

This discussion is preserved as it was. New answers, comments, and votes are closed.