如何在Lua、Love2D中用表格替换打印字符串?

当我按鼠标右键时,我一直试图打印“mode”表中的第二个字符串。 但是当我点击按钮时,它会打印“mode:1”而不是“mode:circle”。 这是我的代码:

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

有人可以告诉我我做错了什么并纠正我吗?

点赞
用户2726734
用户2726734

next返回序号和值,但不保存状态,因此有第二个参数,你需要传递前一个序号。

通常是这样的 nextIndex,nextValue = next (mytable,previousIndex)

在你的例子中,currentMode 被分配为 nextIndex ,它是 "circle" 的索引,值为2。

以下是一个工作示例:

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
2015-01-10 22:53:54