Posted 16 January 2013 - 03:37 PM
Hello, I was wondering if there was a way that I could copy information from one variable over to another
local var1 = 1
print( var1 ) -- prints 1
local var2 = var1
print( var2 ) -- prints 1
var1 = var1 + 1
print( var1 ) -- prints 2
print( var2 ) -- prints 1
However beware, some variables (such as tables) are a reference to where the variable is store in memory, meaning when you use = you are just copying the reference, not the actual value you want.
local var1 = { 1 }
print( var1[1] ) -- prints 1
local var2 = var1
print( var2[1] ) -- prints 1
var1[1] = var1[1] + 1
print( var1[1] ) -- prints 2
print( var2[1] ) -- prints 2
you would need to do the following
local function copyTable( table )
local t = {}
for k, v in pairs( table ) do
t[k] = v
end
return t
end
local var1 = { 1 }
print( var1[1] ) -- prints 1
local var2 = copyTable( var1 )
print( var2[1] ) -- prints 1
var1[1] = var1[1] + 1
print( var1[1] ) -- prints 2
print( var2[1] ) -- prints 2