“quit”读作空字段 (nil field)?

我正在制作游戏的菜单文件,但无法将其调用为“quit”字段。它总是返回nil。有人能告诉我为什么会发生这种情况吗?请注意,它在代码中早先声明,而其他按钮功能确实起作用。谢谢!

function love.mousepressed( x, y, button )
  if button == "l" then
    for k, v in pairs(buttons) do
      local ins = insideBox( x, y, v.x - (v.w/2), v.y - (v.h/2), v.w, v.h)

      if ins then
        if v.action == "play" then
          loadState("game")
        end
      end
      if ins then
        if v.action == "quit" then
          love.event.quit()
        end
      end
    end
  end
end
点赞
用户501459
用户501459

为什么你会将 playquit 绑定到同一个按钮上呢?o.O

另外,检查 ins 两次是没有必要的。重复的代码应该要引起关注:

  if ins then
    if v.action == "play" then
      loadState("game")
    end
  end
  if ins then
    if v.action == "quit" then
      love.event.quit()
    end
  end

可以这样写:

  if ins then
    if v.action == "play" then
      loadState("game")
    elseif v.action == "quit" then
      love.event.quit()
    end
  end

但是,如果没有使用调试器,以下是如何跟踪此类问题的方法:

1. 在项目文件夹中创建一个名为 conf.lua 的文件。

2. 至少需要在文件中添加以下代码,以将控制台附加到应用程序:

function love.conf(t)
    t.console = true  -- 将控制台附加到应用程序(仅限 Windows)
end

3.mousepressed 函数中添加调试输出,这样您就可以看到发生了什么。

首先在应用程序执行的早期定义以下内容,这是一个方便的打印函数:

 function printf(...) print(string.format(...)) end

然后向函数添加一些调试内容:

 function love.mousepressed(x, y, button)
     print('mouse button %d pressed at %d, %d', button, x, y)
     if button == "l" then
         printf('checking %d buttons', #buttons)
         for k, v in pairs(buttons) do
             local ins = insideBox( x, y, v.x - (v.w/2), v.y - (v.h/2), v.w, v.h)
             printf('%d, %d is%sinside button %s (%d, %d, %d, %d)',
                 ins and ' ' or ' not ', k, x, y, v.x, v.y, v.w, v.h)
             if ins then
                 print('executing action', v.action)
                 if v.action == "play" then
                     loadState("game")
                 elseif v.action == "quit" then
                     love.event.quit()
                 end
             end
         end
     end
 end

还应该使用有意义的变量名。v 可以是 buttonk 是什么?一个索引吗?那么可能是 iindex。是一个名称吗?那么是 name。诸如此类。k 不告诉我们任何信息。

2015-10-23 17:30:52