【问题标题】:Error: bad argument #1 to 'strfind' (string expected, got nil) in Lua错误:Lua 中 'strfind' 的错误参数 #1(字符串预期,得到 nil)
【发布时间】:2019-10-13 16:22:22
【问题描述】:

这是代码:

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 Byte Order Mark
      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

我不是一个经验丰富的“脚本编写者”,所以我真的不知道如何解决这个问题。

【问题讨论】:

  • 如何调用scanwhite
  • 我的意思是这是一个下载的脚本,我弄乱了一点,然后它告诉我错误在哪里。 pastebin.com/qbkmQaqx 有完整的脚本。错误在第 397 行
  • 如何调用json.decode?给出使用示例,以便我们可以重现错误。顺便说一句,还有其他 JSON libraries.

标签: lua


【解决方案1】:

前面的底线:

  • 问题:scanwhite(str, pos) 中的“str”为 nil
  • 为什么?
    • 您可能写的是 scanwhite() 而不是 scanwhite("something goes here")
    • 您可能传递了一个空变量而不是包含字符串的变量

详细解答

来自 lua 2.4 手册:

strfind (str, substr, [init, [end]])
  • 方括号表示可选,方括号外为必填项。
  • 您的错误消息显示 “字符串预期,得到了 nil”,因此必填项为空
  • 在您的代码中,substr 显然不为空(它是“%S”)
  • 推论str为nil值

解决方案:

local myString = "This is a string"
scanwhite(mystring)

【讨论】:

    猜你喜欢
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 2019-08-16
    相关资源
    最近更新 更多