Need help with modular code

Hey i have been scripting on Roblox for just under a year. I’m starting to try and use modules more and have used leif’s video for knowledge of what a good structured game looks like and now im trying to create some systems using the structure. Is this the right way of coding in this structure or do i need to use OOP for everything?
Thanks!

local Players = game:GetService("Players")
local SSS = game:GetService("ServerScriptService")
local RP = game:GetService("ReplicatedStorage")
local RS = game:GetService("RunService")

local DataManager = require(SSS.Modules.DataManager)
local ProfileStore = require(RP.Packages.ProfileStore)
local DataTemplate = require(RP.Shared.Modules.DataTemplate)

local PlayerDataService = {}

function PlayerDataService.init()
	PlayerDataService.profileStore = ProfileStore.New(PlayerDataService.getStoreName(), DataTemplate)
	Players.PlayerAdded:Connect(PlayerDataService.onPlayerAdded)
	
	for _, player in Players:GetPlayers() do
		task.spawn(PlayerDataService.onPlayerAdded, player)
	end
	
	Players.PlayerRemoving:Connect(PlayerDataService.onPlayerRemoving)
end

function PlayerDataService.onPlayerAdded(player: Player)
	local profile = PlayerDataService.profileStore:StartSessionAsync("Player_" .. player.UserId, {
		Cancel = function()
			return player.Parent ~= Players
		end,
	})
	
	if not profile then
		player:Kick()
		return
	end
	
	profile:AddUserId(player.UserId)
	profile:Reconcile()

	profile.OnSessionEnd:Connect(function()
		DataManager.Profiles[player] = nil
		player:Kick()
	end)
	
	if player.Parent == Players then
		PlayerDataService.createLeaderstats(player, profile)
		DataManager.Profiles[player] = profile
	else
		profile:EndSession()
	end
end

function PlayerDataService.onPlayerRemoving(player: Player)
	local profile = DataManager.Profiles[player]
	if profile then
		profile:EndSession()
	end
end

function PlayerDataService.createLeaderstats(player: Player, profile)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Value = profile.Data.Coins
	coins.Parent = leaderstats
end

function PlayerDataService.getStoreName()
	if RS:IsStudio() then
		return "TEST_0"
	else
		return "LIVE_0"
	end
end

return PlayerDataService
1 Like

First of all, you don’t need to use OOP for anything. OOP is one way of doing something, but it’s not always the best way. If you work alone, I would personally just recommend you to find a style that works for you.
Anyways do you plan on using any function except init from outside of the module?
If no, you can just make them local functions.

1 Like