We need to return the new structure from the meta table

Hi all.
I created a class. It has a class structure. For example inventory, weapons, car, whatever. I need to return the structure from the class.
The autocomplete should work.
No matter what I do, I get the same array back. I need different ones.

Class

local Class = {}
 

local Struct = {
	name = "Def name",
	descr = "Text",			
	max = 110,
	def = 1,
	val= 0,
};
 

function TCopy(t)
	local r = {}
	for k, v in pairs(t) do
		r[k] = v
	end
	return r
end


function Class.new() 
	local ReturnStruct =  Struct;

     --If you copy the original table, everything works correctly. But it's not a pretty solution.
	--Struct=TCopy(Struct);  

	return ReturnStruct;
end

function Class.GetState() 
	
	return 1;
end


return Class;

Include

local  CLASS_Test = require(script.Parent.CLASS_Test);


local Obj1 = CLASS_Test.new();

 

local Obj2 = CLASS_Test:new();
Obj2.name ="BB2";


print(Obj1.name, Obj2.name)


if(Obj1.name ~= Obj2.name)then
	warn("This work");
else
	warn("It is the same object.");
end

Autocomlete. That’s what I mean.
aco

The sourcebook I work with.
saffasfasf.rbxl (21.8 KB)

Tables are passed by reference, so no two tables are the same. Try ={ } ~= { } in the console and see the output, you should see false since it’s 2 constructed tables. You’ll have to go with copying the table sadly.

1 Like

Isn’t there any other way? There are many frameworks, do they copy tables too?

Yes, they also copy tables. It’s really not that big of a deal to copy a table, or I don’t know why you don’t want to do it.

Struct = TCopy(Struct)
I don’t like it because of the extra function you have to keep inside. And in itself looks like a crutch.
I found a built-in (low level) function. It looks more correct.

Struct = {table.unpack(Struct)}