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 ?

Upvotes: 3

Views: 1815

Answers (2)

Paul Kulchenko
Paul Kulchenko

Reputation: 26774

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

Upvotes: 6

lhf
lhf

Reputation: 72352

Use #newtable instead of table.maxn(newtable).

Upvotes: 2

Related Questions