Is it better to keep data in global tables/dictionaries, or make them in the scirpt?

I am making a survival game. i have a dictionary that includes the amount of wood/stone/gold and other objects that are needed to craft an item. I only have two scripts that need this info: the clientGUI (crafting system), and the server which deducts the items. I’m wondering, is it better to store this in a global dictionary, and if so, how would I do that?

1 Like

I would use a ModuleScript (roblox.com), add the functions:

function module.addItem(player: Player, item: string, amount: number)

function module.removeItem(player: Player, item: string, amount: number)

function module.getInventory(player: Player)

This should make it somewhat easy to keep track of which items the player does/doesn’t have. To let the player get access to the inventory (only allow it to view which items the player has, not change them) you could add a remote function:

remoteFunction.OnServerInvoke = function(player)
	return module.getInventory(player)
end)

This will return the inventory of the player who asked to see their inventory.

Apologies for possibly being to vague, but I was asking about whether I should make dictionaries for how much the craftables cost - as I would have to change both scripts if I wanted to add one craftable.

You are thinking right regarding having to update things on multiple places, you should avoid repeating yourself as much as possible when it comes to programming.

I would still use a module script for this, a module script is just a table which multiple scripts can have access to (more or less). The following script may be better suited for you if you require crafting costs:

local module = {}
local craftingCosts = {
	["Bow"] = {
		["Stick"] = 3,
		["String"] = 3,
	},
}


function module.getRecipes()
	return table.clone(craftingCosts)
end

return module

By making craftingCosts a separate table to module you are preventing scripts from gaining access to the actual recipes, instead they get access to a cloned table. This is helpful to prevent accidental modification from other server scripts, but not a requirement.

1 Like