Which one is better? (elseif or functions)

if Level == 1 then 
		Textlabel.Text = Info.."★"
		ShowEffect(true, Level)
	elseif Level == 2 then 
		Textlabel.Text = Info.."★★"
		ShowEffect(true, Level)
	elseif Level == 3 then 
		Textlabel.Text = Info.."★★★"
		ShowEffect(true, Level)
	elseif Level == 4 then
		Textlabel.Text = Info.."★★★★"
		ShowEffect(true, Level)
	elseif Level == 5 then 
		Textlabel.Text = Info.."★★★★★"
		ShowEffect(true, Level)
	else
		Textlabel.Text = player:GetAttribute("RoleInGroup_33779157")
		ShowEffect(false, 0)
	end

or

local wantedFunctions = {
	[1] = function(Textlabel)
		Textlabel.Text = Info.."★"
	end,

	[2] = function(Textlabel)
		Textlabel.Text = Info.."★★"
	end,

	[3] = function(Textlabel)
		Textlabel.Text = Info.."★★★"
	end,

	[4] = function(Textlabel)
		Textlabel.Text = Info.."★★★★"
	end,

	[5] = function(Textlabel)
		Textlabel.Text = Info.."★★★★★"
	end,
}
if Level >= 1 then
		ShowEffect(true, Level)
		wantedFunctions[Level](Textlabel)
	else
		Textlabel.Text = player:GetAttribute("RoleInGroup_33779157")
		ShowEffect(false, Level)
	end
2 Likes

string.rep:

if (Level >= 1) then
    TextLabel.Text = Info .. string.rep("★", Level)
    ShowEffect(true, Level)
else
    Textlabel.Text = player:GetAttribute("RoleInGroup_33779157")
    ShowEffect(false, Level)
end
1 Like

The second one is better. Also, I like the response that Rumble gave.

CHATGPT Response:

  1. Reduced Conditional Checks: The second script eliminates multiple conditional checks (if-elseif) and directly accesses the function from the table based on the Level value. This reduces the number of conditional branches the code has to go through.
  2. Function Lookup: In Lua, table lookups are generally faster than conditional branches. By storing functions directly in a table and accessing them by index (Level in this case), the second script bypasses the need for multiple comparisons (if-elseif) and directly calls the appropriate function.
  3. Code Readability and Maintenance: While speed optimization is important, readability and maintainability are also crucial factors. The second script, though a bit more complex, offers better modularity and ease of maintenance due to the clear separation of functionality within the table.
1 Like

Thank you so much. I really appreciate it

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