How would I go about making a shared table with metatables? (with ModuleScripts)

Hello! I want to make a table accessible by scripts requiring the module, and I heard that it was possible to do with metatables.

However I don’t know where to start.

Could someone please help me?
(I’m trying to make a player data saving system, btw.)

1 Like

You can just return a table in the module script and it will be shared.

Metatables are not necessary for sharing a table.

4 Likes

No, as the values aren’t shared.

1 Like

Yes they will be, unless you are dealing with server client differences then you will need remote events. The table is created 1 for server and 1 for client if required by both.

1 Like

No, as the values aren’t shared.

Module:

local module = {}

module.points = 0

return module

Script 1:

local module = require(modulescript)
module.points = 7

Script 2:

local module = require(modulescript)
print(module.points) -- Will print 0
2 Likes

Sounds like a race condition. This is what happens when you rely on strict timing for code rather than defensive architecture; but also when you assume that both your scripts will run sequentially in the order you made them. Script “2” could be running before Script “1”. There is a “simple” fix but I don’t want to teach it to you because it’s a noob trap, all it’ll do is highlight the timing issue.

The state of a ModuleScript is shared between VMs: those are server, client, command bar, plugins and those four when in an Actor context (code parented under an Actor). Use of metamethods is unnecessary for creating “shared” content and you will experience the same problem. Use metatables only if your use case actually needs one, which in this case you really don’t.

6 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.