I thought I understood how a variable worked with a variable being assigned an address in memory where you can store a value, though evidently I don't. I have this small snippet of code here that finds certain combination of numbers that fit into a bigger number. My issue is where if result == 0 then I try to copy the value of priorPath to a different variable completedPath, then add list[i] into the table completedPath, and then store completedPath into another table storing all possible paths. My issue is that any changes to completedPath all show up on priorPath which I don't want to happen. So back to the original question, how do I declare a variable of equal value using a different memory address?
local function testNumber(number, exit)
if number > exit then return false end
return exit - number
end
local function getPaths(list, goal, priorPath, paths)
--print(goal)
for i = 1, #list do
local result = testNumber(list[i], goal)
if result == 0 then
local completedPath = priorPath
table.insert(completedPath, list[i])
table.insert(paths, completedPath)
elseif result then
table.insert(priorPath, list[i])
paths = getPaths(list, goal - list[i], priorPath, paths)
end
end
return paths
end
Edit: I ended up having to do something stupid like the following, and it worked, any better solutions?
local function testNumber(number, exit)
if number > exit then return false end
return exit - number
end
local function getPaths(list, goal, priorPath, paths)
for i = 1, #list do
print(list[i])
local result = testNumber(list[i], goal)
if result == 0 then
local newTbl = {}
for k,l in pairs(priorPath) do
table.insert(newTbl, l)
end
table.insert(newTbl, list[i].." ")
table.insert(paths, newTbl)
elseif result then
local newTbl = {}
for k,l in pairs(priorPath) do
table.insert(newTbl, l)
end
table.insert(newTbl, list[i])
paths = getPaths(list, goal - list[i], newTbl, paths)
end
end
return paths
end

1 comment
I would assume this behavior varies from language to language? Such that in Java something like an ArrayList might not be a pass-by-reference?