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