简体   繁体   中英

Getting attempt to call a nil value (field 'maxn') error

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

I'm getting this error when I run it in terminal :

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 ?

But when I try to run it on tutorialspoint compiler it runs.

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

This should be my output. I couldn't pinpoint what is exactly the problem here since it runs on tutorialspoint coding ground lua compiler.

What should I change for it to work on my terminal ?

From Lua 5.2 Reference Manual - 8.2 – Changes in the Libraries :

Function table.maxn is deprecated. Write it in Lua if you really need it.

You are running a more recent version of Lua than tutorialspoint.

You can add the following code at the top of your script that will make it work in Lua 5.1+ versions:

table.maxn = table.maxn or function(t) return #t end

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM