Accessing metatables from other scripts

So basically I’m trying to access a metatables from different scripts and I’d like to know if there’s a proper way of doing so.

I’ve tried using BindableFunctions, but after losing quite a few hair when trying to figure out what wasn’t working with my code and doing some search on the devforum, I figured out that “BindableFunctions can’t pass back any sort of self-referential table” on this post : Cannot access metatable through BindableFunction

Could you use a global table to achieve this?

local data = {}
_G.test = setmetatable({}, {__index = data})

No, don’t do that. Instead use a module script. You should never use globals or _G or shared. Use of globals is bad practice, it makes your code messy. There was just a discussion about this which you should check out.

Module scripts cannot share information with other scripts though.

That is incorrect. Modules were made for just that.

local mt = require(mt_module)

It would be the same reference.

The context of this problem was how to access a metatable from other scripts, of course you can put a metatable inside of a module.

local data = {}

function data.new()
    local self = setmetatable({},{__index = data})
    return self
end

I was merely answer his question in the context he was describing

I do not understand what you are saying. My point is, modules are a much better solution to this and can do just that.

2 Likes

Oh I just did a test, I had the idea that modulescripts run the code each time required. I suppose I was incorrect in that matter, I’ve learned something new :slight_smile: thx

can you insert data into a metatable in a module, through another script?

I mean, you could use ModuleScripts in a static manner like so:

local data = {}

local module = {}

function module:GetData()
    return data
end

function module:SetData(d)
    data = d
end

return module
1 Like

yes you can

Since require caches its result the result will be the exact same reference across scripts.

1 Like

Thanks. I had a very strange issue when using _G and now that I’m using modules it seems to be working.