尝试索引 local 'args'(一个函数值)

Attempt to index local 'args' (a function value)

我试图通过将 gmatch 与 %S+ 一起使用来将字符串拆分为 table。然而我运行进入错误:

Attempt to index local 'args' (a function value)

以下是我认为有问题的三行代码:

print(msg)
local args = string.gmatch(msg, "%S+")
print(args[1])

所以第一行 print(msg) 只是打印了一个正常的字符串,这是应该的。第二行假设用空格分割该字符串,并将 table 存储在 args 中。第三行应该打印 table 中的第一个值,但它却给我上面显示的错误。谢谢。

string.gmatch 没有 return 结果如您所愿;它 return 是一个迭代器(一个特殊函数),然后您可以在循环中使用它来获取所需的值。这就是为什么当您尝试索引 returned 函数时会出现该错误。

您可以查看 the documentation or this SO question 以获取有关如何使用 gmatch 获取值的示例。