Cleaner way of going through item ids?

I have a shop in game where players can purchase items. Works by sending the server a signal with the player information and item id

emeraldShopPurchase.OnServerEvent:Connect(function(player, id)
	if id == 1 then
		--Do Something
	elseif id == 2 then
		--Do Something
	elseif id == 3 then
		--Do Something
	elseif id == 4 then
		
	end
end)

This is something I have in mind for the shop that I know will work, but I was wondering if there was a cleaner way of doing this?

You could use a table and store the information related to the item in the table. Price, the function it should run when purchased(in the event they do different things upon purchased), etc.

So you would just check if the item exists in the table and do what you need to do after, take money away, spawn the item, give them an item, etc.

2 Likes

A cleaner way would be to store the information of the shop items in a module script placed in serverstorage. Access the module script using require(game:GetService("ServerStorage").ModuleScript), in the module script you can basically store all the items and their information using tables/arrays.

Module Script would look like:

local shop = {}

shop.Items={
	[120401230]={
		["Name"]="Banana";
		["Price"]=50;
		["Description"]= "A yellow fruit!"
	};
	
}

return shop

Now, in the script, to make it cleaner, turn your code into a different function above, by:

local shop=require(game:GetService("ServerStorage").ModuleScript)

function onShopPurchase(player,id)
	if shop.Items[id] then
		----do your thing here
	end
end

And yeah, don’t forget to connect the function.

emeraldShopPurchase.OnServerEvent:Connect(onShopPurchase)
1 Like

I don’t see how this will make the code cleaner, I want it so that each id will trigger a function in the module when I pass an id through

Example:

local shop = {}

shop.Items = {
	[1] = function()
		print("Item: 1")
	end,
	[2] = function()
		print("Item: 2")
	end,
	[3] = function()
		print("Item: 3")
	end,
	[4] = function()
		print("Item: 4")
	end,
}
return shop

1 Like

You only have to check if the Id exists in the table, as opposed to creating a new if / elseif / else statement for each one.
It also keeps the MainScript from being excessively long and using ModuleScripts for things like this, are really great. You could also reference the ModuleScript for the Client and Server if you want to, by putting it inside ReplicatedStorage.

It may not seem like a lot, but its probably the best way of keeping things organized.