unintentional change to a table
Posted: Sun Dec 04, 2011 1:03 pm
Hi,
I'm trying to do the following thing.
I have a table, say
Now I wrote a function that can add values to it from a similar set, like such:
The problem is that, even though I'm adding values to the table 'setToBeReturned', the new values show up in the original table, 'set', even though I explicitly tell the function to copy the values from the original table into the table 'setToBeReturned'. This gives problems in the next program, where I'm telling Lua to stop substracting from the main table if one of the values is zero. It recognizes that but still keeps on substracting. what am I doing wrong? (instructions: run code and press spacebar 11 times to see the amount of gold go negative)
I'm trying to do the following thing.
I have a table, say
Code: Select all
set = { { name = "gold", amount = 10 },
{ name = "silver", amount = 100 } }
Code: Select all
function addSet(setToBeAdded, s)
local setToBeReturned = s
for k1, v1 in ipairs(setToBeAdded) do
for k2, v2 in ipairs(setToBeReturned) do
if v1.name == v2.name then
v2.amount = v2.amount + v1.amount
end
end
end
return setToBeReturned
end
Code: Select all
local set = {}
local success
function love.load()
set = { { name = "gold", amount = 10 },
{ name = "silver", amount = 100 } }
success = true
end
function love.draw()
for k, v in ipairs(set) do
love.graphics.print(v.amount, 0, k * 20)
end
if success == true then love.graphics.print("can substract", 100, 0)
else love.graphics.print("cannot substract", 100, 0)
end
end
function love.keypressed(key, unicode)
-- when spacebar is pressed...
if unicode == 32 then
--add increment to set and store result in newSet
increment = { { name = "gold", amount = -1} }
newSet = addSet(increment, set)
--check if none of the values are negative
success = true
for k, v in ipairs(newSet) do
if v.amount < 0 then
success = false
end
end
--if none of the values are negative, copy newSet into set
if success == true then set = newSet end
end
if key == "q" or key == "escape" then
love.event.push("q")
end
end
function addSet(setToBeAdded, s)
local setToBeReturned = s
for k1, v1 in ipairs(setToBeAdded) do
for k2, v2 in ipairs(setToBeReturned) do
if v1.name == v2.name then
v2.amount = v2.amount + v1.amount
end
end
end
return setToBeReturned
end