How to copy a table from a module script

To explain the situation better I’ve set up some example code:

Module Script

local t = {Value = 1}

local module = {}

module.T = function()
	print("Module value = "..t.Value)
	return t
end

return module

Server Script

local module = require(script.Parent.ModuleScript)

while task.wait(1) do
	local myT = module.T()
	myT.Value = 2
	print("Server script value = "..myT.Value)
	print('--------')
end

Output
image

As shown in the picture the module value changes when the server script sets the value. My goal is to have the script not set the module value but set the server script value alone. My intended output is to have it go in a 1,2,1,2 pattern, not a 1,2,2,2 pattern.

1 Like

You need to create a new version of the module script. I’m not sure how to explain it so I’ll provide an example (with the code you provided) below:

Module Script:

local t = {Value = 1}

local module = {}
module.__index = module

function module.new()
	local self = setmetatable({},module)
	self.Value = t.Value
	return self
end

function module:T()
	print("Module value = "..self.Value)
	return t
end

return module

Server Script

local moduleScript = require(script.Parent.ModuleScript)
local module = moduleScript.new()

while task.wait(1) do
	local myT = module:T()
	myT.Value = 2
	print("Server script value = "..myT.Value)
	print('--------')
end
1 Like

Use a local variable for the module, and a separate table for the server script. This keeps the module’s variable unchanged as the server script in your code is directly accessing the module and changing its value through a function in the module.

Creating a variable in the module and a function to create a separate table just for the server script to change is a way you could use to approach this. In that way, the server has it’s own local table as well as the module.

Module Script

local MainT = {Value = 1}

local TAB = {}
TAB.__index = TAB

function TAB.new()
	local NewTable = {Value = 1}
	setmetatable(NewTable, TAB)
	
	print("Module Value = "..MainT.Value)
	print('--------------')
	
	return NewTable
end

return TAB

Script

local tab = require(script.Parent.TAB)

while task.wait(1) do
	local myT = tab.new()
	myT.Value = 2
	
	print('Server Script value = '..myT.Value)
	print('---------------')
end

Just adding a little bit more detail to @spoopmoop post.

4 Likes

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