【问题标题】:file:write() error: "bad argument #1 to 'write' (string expected, got nil)"文件:写()错误:“'写'的错误参数#1(字符串预期,得到零)”
【发布时间】:2019-11-06 18:40:01
【问题描述】:
local log = io.open("log.txt","a")
local logText

for i=1,8 do --in case you claim this is pointless, it's here because it might affect the outcome and it has a use in other places of my program
  if a == 1 then --throwaway variable for this example
    press = 4; logText = "A = 1."
  else
    press = 8; logText = "No other rules apply."
  end

  if i == 8 then
    log:write(logText)
    log:write("\nCorrect combination: "..press.."\n") --claims error is here
    log:close()
  end
end

第二个log:write() 抛出一个错误(bad argument #1 to 'write' (string expected, got nil)),声称当我直接在函数中输入它时它没有字符串,这让我非常恼火。但是,该错误并非总是发生 - 其他时候,它可以完美运行,似乎没有任何理由。其次,当我在上面的if 语句中输入log:write() 时,它现在认为错误与if 语句一致,例如:

if press ~= 0 then --claims error is here
  log:write("\nCorrect combination: "..press.."\n")
end

我的程序中有多个重复的这个代码示例,具有不同的变量/值,并且我已经多次验证它们都是相同的。

这可能会引发什么错误,为什么?

【问题讨论】:

  • 您的示例是否重现了错误?似乎没有。最好的猜测是这是因为 presslogText 在某些情况下可能是 nil (再次 - 在您的示例中不可重现)。在文件开头尝试local logText = ""; local press = 0
  • 遗憾的是,仍然出现同样的错误。
  • 如果需要,我可以把整个文件发给你。
  • 取决于文件的大小。我希望有一个重现问题的示例。如果您不能这样做,我们可以尝试使用整个文件来解决。
  • 问题是我不确定是什么导致了问题。我不知道问题是 IDE(最近抛出了关于 OLD 代码的错误,请参阅:imgur.com/a/jvXJMot)还是代码本身。

标签: lua


【解决方案1】:

尽管在问题的示例中无法重现,但以类似方式编写的脚本有可能presslogText 仍然是nil。那是因为它们仅在程序的选定分支中被赋予它们的值。

尝试事先为它们分配“空”值以避免nil 连接问题或io.write

local log = io.open("log.txt","a")
local logText = ""
local press = 0

-- Rest of the logic.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 2018-11-18
    • 2020-05-19
    • 1970-01-01
    • 2021-07-29
    相关资源
    最近更新 更多