Get a cloned table when referenced

Hello folks, I am having a hard time using metatables.

How would I return a table that gets cloned when indexed??
Here’s my module

local Deepcopy= require(script.Parent.Parent.Utils.DeepCopy) --function that copies everything nested within the table 

local SavedMaps = {}

SavedMaps.SmileyFace = {
	{0,1,0,1,0},
	{0,1,0,1,0},
	{0,0,0,0,0},
	{1,0,0,0,1},
	{0,1,1,1,0},
}

SavedMaps.Dot = {
	{0,0,0,0,0},
	{0,0,0,0,0},
	{0,0,1,0,0},
	{0,0,0,0,0},
	{0,0,0,0,0},
}

SavedMaps.Triangle = {
	{0,0,0,0,0},
	{0,0,1,0,0},
	{0,1,1,1,0},
	{1,1,1,1,1},
	{0,0,0,0,0},
}

--How would I do deepcopy????

return SavedMaps

So when I would call that table, it would return a copy of it

local Presets = require("Presets")
local Matrix = Presets.SmileyFace --> This is a copy of SmileyFace

The reason why I ask this is that lua’s tables are anonymous and the tables within will have its values changed if I didn’t clone which can cause bugs.

i have no idea bro tbh ask chat gpt or something

This doesn’t seem like a very good use case of metatables, you should just have a function that deep copies the table you want instead of implicitly cloning each time it’s indexed (which might be confusing for anyone going through your code too).

1 Like

I know what I am using this module for and deep-copying it every time its index should provide a copy of itself as it is necessary.
I already have the function as a util but I don’t want to require the function in every script that uses this table.

Do you mean you want to do this:

export type Maps = typeof(SavedMaps)
return function()
	return Deepcopy(SavedMaps) ::Maps
end

On requiring

local Presets = require("Presets")() --Call the function on requiring
local Matrix = Presets.SmileyFace

Edit: just added the typecasting for intellisense

You might know what it does right now, but that doesn’t mean you will 6 months from now.

You don’t have to require DeepCopy from every script if you just implemented a GetMap function in the module.

2 Likes

I don’t really want to do that as outside of the module, it’ll be too excessive.
I can simply put down comments on my code for why its there.

Implement a “GetMap” function in the module.

Something like this:

function SavedMaps.GetMap(mapName: string)
	return Deepcopy(SavedMaps[mapName])
end

Less confusing, more efficient.

2 Likes

I guess I’ll have to compensate and use this then…
Not really what I wanted to do but if I must…

You can use metatables if you really wanted to, but there’s not really any point in your use case, it’ll just make it more confusing and less efficient.

1 Like

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