lua的语法问题:wrong number of arguments to ‘insert’

2024/03 20 10:03
-- 语句1
local item = getItem()
table.insert(list, item)

-- 语句2
table.insert(list, getItem())

以上2个语句,一般来说,语句2可以直接替代语句1,但是他们是不等价的

local function getItem()
  ..
  return
end

如果getItem的返回值是return或者没写,语句2就会出错

wrong number of arguments to 'insert'
stack traceback:

因为insert是这样写的

static int tinsert (lua_State *L) {
  int e = aux_getn(L, 1) + 1;  /* first empty element */
  int pos;  /* where to insert new element */
  int c = lua_gettop(L);
  switch (c) {
    case 2: {  /* called with only 2 arguments */
      pos = e;  /* insert new element at the end */
      break;
    }
    case 3: {
      pos = luaL_checkint(L, 2);  /* 2nd argument is the position */
      ...
      break;
    }
    default: {
      return luaL_error(L, "wrong number of arguments to " LUA_QL("insert"));
    }
...

所以当getItem没有返回值时,栈里参数个数等于1(即list)
table.insert(list, getItem())的调用等同于 table.insert(list),即发生wrong number of arguments to错误