问题描述
我正在使用 Lua 和 lovE2D 创建许多游戏,但是每当我实现一个新功能并想对其进行测试时,或者只是想知道 Lua 中某个变量的值时,我要么将其显示在游戏屏幕上,要么只是希望它有效。
现在我的问题是...
有没有办法在终端或其他地方显示一些信息,例如变量值或其他东西?就像 javascript 中的 console.log
一样,它在浏览器的 javascript 控制台中显示一些内容。那么,Lua 有没有办法做到这一点?使用 lovE2D?
我使用的是 Mac,所以我有一个 terminal
而不是命令提示符。有没有办法在那里显示一些内容?其他任何地方也都可以,我只需要看看这些值是否符合预期。
解决方法
使用 conf.lua
文件来启用控制台,那么您应该可以使用标准的 print()
。您可以阅读维基条目 here。
您只需将 conf.lua
文件添加到 main.lua
所在的位置。您的文件可能像这样简单:
function love.conf(t)
t.console = true
end
但是可以随意从上面的链接复制整个配置文件并编辑您需要的内容。
我不能完全确定这一点,因为我无法访问 Mac,但控制台默认处于禁用状态,即使在 Windows 上,在您打开它之前也不会显示任何打印内容。
或者您还可以像某些游戏一样在游戏本身中显示调试信息。
我喜欢做的是添加类似 debugVariable = {}
来记录每个循环中发生的事件,添加 debugPermanent = {}
来记录很少发生的事件。可能添加方便的函数来写入变量:
function debugAddVariable(str)
table.insert(debugVariable,str)
end
--..and similarly for debugPermanent
现在是绘制调试信息的函数:
function debugDraw()
love.graphics.push() --remember graphics state
love.graphics.origin() --clear any previous transforms
love.graphics.setColor(--[[select color for debug info]])
love.graphics.setFont(--[[select font for debug info]])
for i,v in ipairs(debugPermanent) do
love.graphics.print(v)
love.graphics.translate(0,--[[fontHeight]])
end
for i,v in ipairs(debugVariable) do
love.graphics.print(v)
love.graphics.translate(0,--[[fontHeight]])
end
debugVariable = {} --clear debugVariable to prepare it for the next loop
love.graphics.pop() --recall graphics state
end
我们只需在 love.draw()
的末尾调用这个 draw 函数,文本就会出现。
显然,这种方法几乎可以无限地进一步细化,显示特定变量,为其他一些变量添加图表以阐明您想要显示的信息,但这有点超出了问题的范围。
最后请随时检查用户提交的调试库的 here。