Is there a way to make this code better?

Is there a way to make this code better?


StageChanged.OnClientEvent:Connect(function()
	if leaderstats.Value == 1 then
		cando = true
		Text.Text = "Candy Land!"
	elseif leaderstats.Value == 2 then
		cando = true
		Text.Text = "Desert Land!"
	elseif leaderstats.Value == 3 then
		cando = true
		Text.Text = "Snow Land!"
	elseif leaderstats.Value == 4 then
		cando = true
		Text.Text = "The Fall Land!"
	elseif leaderstats.Value == 5 then
		cando = true
		Text.Text = "Storage Land!"
	elseif leaderstats.Value == 6 then
		cando = true
		Text.Text = "Picnic Land!"
	elseif leaderstats.Value == 7 then
		cando = true
		Text.Text = "Lava Land!"
	elseif leaderstats.Value == 8 then
		cando = true
		Text.Text = "Labirint Land!"
		
	end
end)

Please go to #help-and-feedback:code-review for this!

you can add a table that execute functions
like this:

local Table = {
    [1] = function()
        cando = true
        Text.Text = "Candy Land!"
    end,

    [2] = function()
        cando = true
        Text.Text = "Desert Land!"
    end

    -- Add the rest here
}

StateChanged.OnClientEvent:Connect(function()
    if Table[leaderstats.Value] then
        Table[leaderstats.Value]()
    end
end)
1 Like

You could have a ModuleScript called StageDatas that just contains a bunch of data about each stage, like their names:

local stageDatas = {
    {
        Number = 1,
        Name = "Candy Land",
    },
    {
        Number = 2,
        Name = "Desert Land",
    },
}

return stageDatas

You can use it like this:

local stageDatas = require(game.ReplicatedStorage.StageDatas)

StageChanged.OnClientEvent:Connect(function()
	local stageNumber = leaderstats.Value
	local stageData = stageDatas[stageNumber]

	local canDo = not not stageData --Convert to bool "trick". Not sure what the var is for tho
	if stageData then
		Text.Text = ("%s!"):format(stageData.Name)
	else
		error(("No stageData for stage no. %d!"):format(stageNumber))
	end
end)

I generally like to keep my game’s data separated from my game’s behavior/logic/data processing when I can.

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