出现 attempt to call a nil value (field 'maxn') 错误

mytable = setmetatable({1,2,3}, {
    __add = function(mytable, newtable)

     for i = 1, table.maxn(newtable) do
            table.insert(mytable, table.maxn(mytable)+1, newtable[i])
    end
    return mytable
end
})

secondtable = {4,5,6}

mytable = mytable + secondtable

for k,v in ipairs(mytable) do
    print(k,v)
end

当我在终端中运行时,出现下面的错误:

lua: metatables4.lua:6: attempt to call a nil value (field 'maxn')
stack traceback:
    metatables4.lua:6: in metamethod '__add'
    metatables4.lua:15: in main chunk
    [C]: in ?

但是当我在 tutorialspoint 编译器上运行它时,它可以运行。

1   1
2   2
3   3
4   4
5   5
6   6

这应该是我的输出。我无法确定问题究竟在哪里,因为它可以在 tutorialspoint coding ground lua 编译器上运行。

我该怎么改才能在终端上运行它?

点赞
用户1442917
用户1442917

从[Lua 5.2参考手册-8.2-库中的更改](https://www.lua.org/manual/5.2/manual.html#8.2):

函数表table.maxn已经不推荐使用。如果确实需要,请用Lua编写它。

你正在运行比tutorialspoint更高版本的Lua。

您可以将以下代码添加到脚本的顶部,以使其在Lua 5.1+版本中工作:

table.maxn = table.maxn or function(t) return #t end
2018-04-12 04:41:50
用户107090
用户107090

使用 #newtable 代替 table.maxn(newtable)

2018-04-12 10:27:52