Does anyone know a better way to do this?

This script is for a custom character creation menu:

local function applyClothing(plr, specifications, save)
	if specifications[1] == 1 then
		
	elseif specifications[1] == 2 then
		
	elseif specifications[1] == 3 then
		
	elseif specifications[1] == 4 then
		
	elseif specifications[1] == 5 then
		
	elseif specifications[1] == 6 then
		
	end
end

Is there a way to run code based on what is in this table without doing all the messy elseif stuff?

A lot of languages like Java and C++ have something for situations exactly like this called switch statements. However, Lua does not.

This method of doing it is likely the simplest, and though it may take up space, it is at least easily readable.

I see the name of your function is “applyClothing” so it seems like you’re trying to apply a piece of clothing to a player based on a number from 1 to 6. In this case, you could use a table:

local clothes = {clothing1, clothing2, clothing3, ...}

And then do this:

local function applyClothing(plr, specifications, save)
    local clothing = clothes[specifications[1]]
end
1 Like

You can make a for loop, if u need help with that, you can ask me.

You can also use this post

As another said, a for loop would work:

sample

for i=1, 6, 1 do

   if specifications[1]==i then

   else
     continue
   end

end

Yes, but if I wanted to, say, set a player’s hair color based on the number they provide, would this work? This script works by taking a table containing custom character specifications from the client and applying them on the server. The specifications can be any of six possible options.

edit: wait nvm I just didn’t read your response well, I will try this, thank you.

Another thing that you might do is -

local specifications = {1,2,3,4,5,6} 
local functions = { 
    function on1() 

    end,
    function on2() 

    end , 
--[[ the rest of the functions]] 

} 

local function applyClothing(plr,specification,save) 
    local index = specification[1] 
    functions[index]() 
end

I expect you understand the code but I will just take some time to explain.
You are making a table containing functions that will be called depending on what number the specification[1] is.
If specification[1] == 2 then the function on2() will be called.
Make sure you arrange the table in that an ascending order like in my code.

Thanks! I did something similar to this in the sense that I set the clothing based on the number submitted by the client. It looked like this:

local equippedClothing = clothingPresets[tonumber(specifications[1])]