错误:在Lua中对“strfind”的错误参数#1(期望字符串,实际获得NIL)

这是代码:

local function scanwhite (str, pos)
  while true do
    pos = strfind (str, "%S", pos)
    if not pos then return nil end
    local sub2 = strsub (str, pos, pos + 1)
    if sub2 == "\239\187" and strsub (str, pos + 2, pos + 2) == "\191" then
      -- UTF-8 字节顺序标记
      pos = pos + 3
    elseif sub2 == "//" then
      pos = strfind (str, "[\n\r]", pos + 2)
      if not pos then return nil end
    elseif sub2 == "/*" then
      pos = strfind (str, "*/", pos + 2)
      if not pos then return nil end
      pos = pos + 2
    else
      return pos
    end
  end
end

我不是一个有经验的“编写脚本”的人,所以我真的找不出如何解决这个问题。

点赞
用户4889587
用户4889587

简而言之:

  • 问题:在 scanwhite(str, pos) 中,'str' 是空的

  • 为什么?

    • 可能您写的是 scanwhite() 而不是 scanwhite("something goes here")
    • 您可能传递了一个空变量而不是包含字符串的变量

详细回答

从lua 2.4手册中可以得知:

strfind (str, substr, [init, [end]])
  • 方括号表示可选项,方括号外的为必须项。
  • 您的错误消息说“需要字符串,但获得的是nil”,因此必须项为空
  • 在您的代码中,substr 明显不是空的(它是“%S”)
  • 据此推断出,str 的值为空

解决方案:

local myString = "This is a string"
scanwhite(mystring)
2019-10-12 21:50:43