file:write()错误:“错误的参数#1为'write'(字符串期望,为零)”

时间:2019-11-06 09:57:09

标签: lua

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

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

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

1 个答案:

答案 0 :(得分:1)

尽管在本示例中无法从问题中重现该问题,但是用presslogText都以类似方式编写的脚本可能仍然保留nil。这是因为仅在程序的选定分支中为它们提供了值。

尝试预先为它们分配“空”值,以避免nil与串联或io.write有关的问题:

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

-- Rest of the logic.