Lua table.insert 不接受字符串参数

min*_*als 4 lua lua-table

继续学习Lua。

我编写了一个函数,该函数从每一行中删除第一句话,并将结果作为修改后的行表返回,其中删除了第一句话。奇怪的是,table.insert在这样的函数中表现得很奇怪。

function mypackage.remove_first(table_of_lines)
  local lns = table_of_lines
  local new_lns = {}
  for i=1,#lns do
    table.insert(new_lns,string.gsub(lns[i],"^[^.]+. ","",1))
  end
  return new_lns
end
Run Code Online (Sandbox Code Playgroud)

没想到,这给了我以下错误。

[string "function mypackage.remove_first(table_of_lines)..."]:5: bad argument #2 to 'insert' (number expected, got string)
Run Code Online (Sandbox Code Playgroud)

为什么首先是“预期数字”?

来自table.insert文档

在列表中的位置 pos 处插入元素值,向上移动元素 list[pos], list[pos+1], ..., list[#list]。pos 的默认值为#list+1,因此调用 table.insert(t,x) 会在列表 t 的末尾插入 x。

没有提及 的类型要求table.insert。好的,我决定修改示例。

function mypackage.remove_first(table_of_lines)
  local lns = table_of_lines
  local new_lns = {}
  for i=1,#lns do
    local nofirst = string.gsub(lns[i],"^[^.]+. ","",1)
    table.insert(new_lns,nofirst)
  end
  return new_lns
end
Run Code Online (Sandbox Code Playgroud)

现在一切正常。你能解释一下这里发生了什么吗?

Nic*_*las 5

The problem is a bit complicated. It's a collision of three factors:

  1. string.gsub returns two parameters; the second parameter is the number of matches.

  2. table.insert can take 3 parameters. When it is given 3 parameters, the second parameter is expected to be an integer offset defining where to insert the object.

  3. When you do this: func1(func2()), all of the return values of func2 are passed to func1, so long as you don't pass arguments after func2 in func1's argument list. So func1(func2(), something_else) will get only 2 arguments.

因此,当你这样做时table.insert(ins, string.gsub(...)),这将调用 3 参数版本,它期望第二个参数是将对象插入到的索引。因此问题来了。

如果要确保丢弃,则可以将表达式括在括号中:

table.insert(new_lns, (string.gsub(lns[i], "^[^.]+. ", "", 1)))
Run Code Online (Sandbox Code Playgroud)