Lesson 1 Proper Use of ModuleScripts

In Roblox Lua, Modules is a script that: stores code returns something and can be used by other scripts Think of it like a toolbox 🧰 Other scripts open the toolbox and use the tools inside.

local DataService = {}

-- Table that holds ALL player data while server is running
local PlayerData = {}

-- Default data template
local DEFAULT_DATA = {
	Cash = 100,
	Level = 1
}

-- Get data (creates if missing)
function DataService:Get(player)
	if not PlayerData[player.UserId] then
		-- Deep copy default data
		PlayerData[player.UserId] = table.clone(DEFAULT_DATA)
	end
	return PlayerData[player.UserId]
end

-- Add cash safely
function DataService:AddCash(player, amount)
	if typeof(amount) ~= "number" then return end

	local data = self:Get(player)
	data.Cash += amount
end

-- Remove data when player leaves
function DataService:Remove(player)
	PlayerData[player.UserId] = nil
end

return DataService

  
← Back