This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
emufossum13's profile picture

another question about variables

Started by emufossum13, 16 January 2013 - 02:37 PM
emufossum13 #1
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
theoriginalbit #2
Posted 16 January 2013 - 03:40 PM

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.

EDIT: So doing this with a table doesn't work

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
Edited on 16 January 2013 - 02:55 PM