Any better way to do this?

Hello everyone,

I’m making a tag script where players can choose their own tags and I made it like this

RemoteEvent.OnServerEvent:Connect(function(Player,Tag,Command)
	if Command == "GetEquipped" then
		TagList:GetEquippedTags(Player.Name)
	elseif Command == "Equip" then
		TagList:EquipTag(Player.Name,Tag)
	elseif Command == "Unequip" then
		TagList:UnequipTag(Player.Name,Tag)
	elseif Command == "Give" then
		TagList:GiveTag(Player.Name,Tag)
	elseif Command == "Remove" then
		TagList:RemoveTag(Player.Name,Tag)
	end
end

However I’m pretty sure this is bad but I have no idea how to do this in a more cleaner way, any idea how?

Thanks you.

It looks ok, but if you really wanted to, you can do this:

t = { -- table that holds functions
    GetEquipped = function1,
    Equip       = function2,
    Unequip     = function3,
    Give        = function4,
    Remove      = function5
}
RemoteEvent.OnServerEvent:Connect(function(Player,Tag,Command)
    xpcall(function() -- xpcall
        t[Command](Player.Name, Tag) -- Fires function by string name
    end, function() -- custom error handler
        warn"Command Does not Exist!"
    end)
end)

If you dont have a Second Variable, it should be fine as it wont error, the code will ignore it.

1 Like

thanks for the help but may I know why you wrapped it in xpcall rather then checking if the command exist using if statement?

it just uses a custom error handler, if you really wanted to, you can use pcall

local success = pcall(function() -- not xpcall
    t[Command](Player.Name, Tag) -- Fires function by string name
end)

if not success then
    warn"Command Does not Exist!"
end

2 Likes

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