Creating a Global Table

Hi all,

I’m not sure if it’s possible or not and the answer could be ModuleScripts, so please forgive me if this question comes off as dumb. I am attempting to create a table that will update live and be able to be shared across all scripts on the server. (Preferably not the client). I thought that _G.TableName = {} would have achieved this but I have run into issues with other scripts being able to read from it. Here is a watered down example of what I have located in a module script:

_G.Bricks = {}
local Brick = {}
Brick.__index = Brick

function Brick.new(health)
	local prop = {
		Part = Instance.new("Part"),
		Health = health
	}
	
	_G.Bricks[prop.Part] = setmetatable(prop, Brick)
	return _G.Bricks[prop.Part]
end

function Brick:Damage(amt)
	self.Health -= amt
end

return Brick

The server script would look something like this:

local Brick = require(game.ServerScriptService.BrickModule)
local x = Brick.new(100)
print(_G.Bricks) -- nil
print(_G.Bricks[x.Part]) -- this obviously errors

Building on the example above, what I would like to achieve is to be able to call _G.Bricks[instance] from any script in the server. Not just the script that ran the require on the module.

If you print _G.Bricks on any other script it comes up as nil.

I’ve considered storing them in a separate module, but I’m under the impression that modules can’t be live updated, nor can they be called recursively

Any help is greatly appreciated. I can further explain anything if need be

1 Like

It should work, however it will need a delay in order to let it update.

An alternative solution is to use an BindableEvent or signal to get a similar effect such as InstanceAdded to your global table or module.

Screen shot below shows a task.wait() is needed before Script1 edits the table.

2 Likes

It actually wasn’t the wait issue that was occurring in my actual script. I was doing something much more stupid and I’m too ashamed.

If you don’t require the ‘BrickModule’ right at the start of the game it won’t ever update _G. Why? I don’t know. What I’m ashamed of in particular is that I typed up this example and didn’t bother running it. Having it require the script earlier solved the issue

You provided some good insight thought. I appreciate you looking into the issue!

3 Likes

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