· 5 years ago · Sep 20, 2020, 11:52 PM
1local run = game:GetService("RunService");
2
3local module = {}
4module.__index = module;
5
6local sessionLockMessage = "You happened to join before your data finished saving, try rejoining in a few seconds."
7
8local autosaveDuration;
9local datastore;
10local template;
11
12local function errorFunction(err)
13 warn("Unable to do it sadge", err)
14end
15
16local function transformFunction(current)
17 if current and current.L then return; end
18
19 local data = current or template;
20
21 data.L = true;
22
23 return data;
24end
25
26function module.create(tubl)
27 datastore = tubl.datastore;
28 template = tubl.template;
29end
30
31function module.new(player)
32 return setmetatable({
33
34 attributes = {Locked = false, AutosaveDuration = time()};
35 key = player.UserId;
36 player = player;
37 data = {};
38
39 }, module)
40end
41
42function module:get() -- use only for getting via API Call, self.data otherwise
43 local success, data = xpcall(datastore.UpdateAsync, errorFunction, datastore, self.key, transformFunction);
44
45 if success == false or data == nil then
46 self.attributes.Locked = true;
47 data = template;
48
49 self.player:Kick(sessionLockMessage)
50 end
51
52 data.L = nil;
53 self.data = data;
54
55 return data;
56end
57
58function module:set(what) -- use only for saving via API Call, 'self.data.key = value' otherwise.
59 if self.attributes.Locked or run:IsStudio() then return end;
60 self.attributes.Locked = true;
61
62 what = what or self.data;
63
64 xpcall(datastore.UpdateAsync, errorFunction, datastore, self.key, function(current)
65 warn("saved", self.key)
66
67 return what;
68 end)
69
70 self.attributes.Locked = false;
71end
72
73return module;