Simplifying Code

Hello!

I am just here simply wondering if there is anyway to improve this script below, or I am going to have 200 lines of code by the time I have done all of the elements? I am basically just checking with the CurrentElement variable (script.Parent.Name) if it equals “Hydrogen”. If so, making the CombinedElement variable set to the next element in the list, which is “Helium”, as Helium comes after Hydrogen. And this is the same for all of the elements. I have only listed the first five here though, but the script just repeats over and over.

image

You could try using a dictionary.

--[[
structure:
[CurrentElement] = CombinedElement
Where the key is your current element
and the value is your combined element
]]

local elementResults = {
    ["Hydrogen"] = "Helium",
    ["Helium"] = "Lithium"
    --continues
}

local combinedElement = elementResults[currentElement]
4 Likes

If youre trying to add to the atomic element its probably better to put all of the elements in a table and then find and add to the index

local example = {"hydrogen", "helium", "oxygen"}

function nextElement(elementName)

  local foundIndex
  
  --search for index
  for index, currentElement in ipairs(example) do
    if currentElement == elementName then
      foundIndex = index
    end
  end

  --add 1 for this case
  foundIndex += 1

  --get the next element
  return example[foundIndex]
end
1 Like

Thank you for your response, this seems to work but the other reply is a lot more simple and less time inducing to add new elements!

1 Like

Why not use table.find instead?

local elements = {"Hydrogen", "Helium", "Lithium", "Beryllium"}

local function getNextElement(element)
    local index = table.find(elements, element)
    return elements[index + 1]
end

local element = getNextElement("Helium")
print(element) --Lithium
2 Likes

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