WarningSign
WarningSign

Reputation: 27

How do I replace a printed string with tables in Lua, Love2D

I've been trying to print the second string in the "mode" table when I press right mouse button. But when I click the button it prints "mode: 1" instead of "mode: circle". Here is my code:

function love.load()
mode = {"square", "circle"}
currentMode = mode[1]
end

function nextMode()
currentMode = next(mode)
print(currentMode)
end

function love.draw()
love.graphics.print("mode: " .. currentMode, 10, 10)
end

function love.mousepressed(x, y, button)
if button == "r" then
nextMode()
end
end

Can someone tell me what I'm doing wrong and correct me?

Upvotes: 0

Views: 426

Answers (1)

ryanpattison
ryanpattison

Reputation: 6251

next returns the index and value but holds no state, so there is a second argument to which you pass the previous index.

in general nextIndex, nextValue = next(mytable, previousIndex)

In your example your currentMode is being assigned nextIndex which is the index of "circle" and is the value 2.

Here is a working example:

function love.load()
   mode = {"square", "circle"}
   currentIndex, currentMode = next(mode)
end


function love.mousepressed(x, y, button)
    if button == "r" then
       currentIndex, currentMode = next(mode, currentIndex)
    end
end

function love.draw()
   love.graphics.print("mode: "..currentMode, 10, 10)
end

Upvotes: 2

Related Questions