If you store your data in tables, you can use module scripts to access data across scripts. If you insist on using intvalues/stringvalues/boolvalues, then you can take that data, put it in a table, and save it to datastore.
This way you won't have to save/retrieve from datastore every time you want variables. You just have to update when the player joins and leaves the game. (But I would recommend auto saving every couple minutes as something unexpected can always happen. )
Inside module scripts you can have 'global' functions, variables, etc. (not really global but you can access everything inside a module script when you access it.
Start by putting a ModuleScript inside of your ServerScriptService
The default script will look like this:
The code above has module variable. This is is an empty table. The bottom line returns your table. When you acquire to the ModuleScript in another script, you return the module table.
To acquire the module script in another script, type this into a normal script:
1 | myModule = require(game.ServerScriptService.ModuleScript) |
if we print out myModule, we will get a table, but the table is currently empty, so there's nothing in it. Let's change that. Go back to the module script and add a variable to the table.
Putting the name of the variable 'module' will put our variable 'myVar' inside of module.
3 | module.myVar = "Hello World" |
We can also put functions inside of module:
Just remember to put the module variable name in front of it
3 | module.myVar = "Hello World" |
5 | function module.myFunction() |
Back to the regular script, here's how we'd access the function and variables:
1 | myModule = require(game.ServerScriptService.ModuleScript) |
Here's how you'd get the player data using a module script:
06 | function module.loadFromDS(player) |
08 | local S, data = pcall ( function () |
09 | return DataStore:GetAsync(player.UserId) |
12 | if (S and data and not playerData [ player.Name ] ) then |
13 | playerData [ player.Name ] = data |
19 | function module.getData(player) |
20 | return playerData [ player.Name ] |
In the any regular script you can now do this:
1 | myModule = require(game.ServerScriptService.ModuleScript) |
4 | game.Players.PlayerAdded:Connect( function (player) |
5 | myModule.loadFromDS(player) |
8 | local playersData = myModule.getData(player) |