You can write your topic however you want, but you need to answer these questions:
- What do you want to achieve? Keep it simple and clear!
I am attempting to use OOP with my data module.
- What is the issue? Include screenshots / videos if possible!
It says that self.GlobalData is nil even though I spelled it correctly. I get an error at line 95.
here is the code:
local DataService = {}
local IndexTable = {
__index = DataService
}
local MainStore = game:GetService("DataStoreService"):GetDataStore(script:WaitForChild("DataKey").Value)
local RunService = game:GetService("RunService")
local function GetDataType(data)
if typeof(data) == "number" then
return "IntValue"
elseif typeof(data) == "string" then
return "StringValue"
elseif typeof(data) == "boolean" then
return "BoolValue"
end
end
function DataService.new(UserId)
local newData = {}
setmetatable(newData, IndexTable)
local PlayerDataFolder = Instance.new("Folder")
PlayerDataFolder.Parent = game:GetService("ServerStorage"):WaitForChild("GlobalData")
PlayerDataFolder.Name = "Data-"..UserId
local PlayerLocalFolder = Instance.new("Folder")
PlayerLocalFolder.Parent = game:GetService("ReplicatedStorage"):WaitForChild("LocalData")
PlayerLocalFolder.Name = "Data-"..UserId
newData.PlayerId = UserId
newData.Key = "Key-"..UserId
newData.GlobalData = PlayerDataFolder
newData.LocalData = PlayerLocalFolder
game.Players.PlayerRemoving:Connect(function(player)
if player.UserId == UserId then
DataService:SaveData()
end
end)
game:BindToClose(function()
if RunService:IsStudio() then
wait(3)
else
DataService:SaveData()
end
end)
return newData
end
function DataService:CreateNewData(ValueName, DefaultValue)
local ValueObjGlobal = Instance.new(GetDataType(DefaultValue))
ValueObjGlobal.Parent = self.GlobalData
ValueObjGlobal.Value = DefaultValue
ValueObjGlobal.Name = ValueName
local ValueObjLocal = Instance.new(GetDataType(DefaultValue))
ValueObjLocal.Parent = self.LocalData
ValueObjLocal.Value = ValueObjGlobal.Value
ValueObjLocal.Name = ValueObjGlobal.Name
ValueObjLocal.Value = ValueObjGlobal.Value
ValueObjGlobal.Changed:Connect(function()
ValueObjLocal.Value = ValueObjGlobal.Value
end)
local data
local success, err = pcall(function()
data = MainStore:GetAsync(self.Key)
if data then
for _,v in pairs(self.GlobalData:GetChildren()) do
if data[v.Name] ~= nil then
v.Value = data[v.Name]
end
end
end
end)
if not success then
print("error loading data: ")
print(err)
end
end
function DataService:SaveData()
local SaveTable = {}
for _,v in pairs(self.GlobalData:GetChildren()) do
SaveTable[v.Name] = v.Value
end
for k,v in pairs(SaveTable) do
if v == nil then
table.remove(SaveTable, k)
end
end
local success, err = pcall(function()
MainStore:SetAsync(self.Key, SaveTable)
end)
if not success then
print("error saving data")
print(err)
end
end
return DataService