Reputation: 21304
I'm new to Lua, so maybe missed something on tutorials but the problem is:
I have original table and metatable with several operators that I'm applying to it:
original = { 1, 2, 3 }
test = setmetatable(original, {
__add = function (lhs, rhs)
print('adds')
end,
__mul = function (lhs, rhs)
print('multiplies')
end
})
Unfortunately when I'm doing operations like:
test = test + 3
test = test * 3
I receive an error:
attempt to perform arithmetic on global 'test' (a table value)
Didn't find any descriptions on this problem. Also I noticed that if metatable is a separate variable and passed to setmetatable
method then it works..
Upvotes: 2
Views: 107
Reputation: 28991
test = test + 3
Is loosely equivalent to:
test = getmetatable(test).__add(test, 3)
You're assigning the return value of __add
to test
.
_add
returns nothing, so after the first line, test
is nil
. Then you do it again:
test = getmetatable(test).__add(test, 3)
You can't index or get the metatable of nil
.
An easy what to have discovered this, probably the first thing I would have tried:
test = test + 3
print(test)
test = test * 3
Upvotes: 5
Reputation: 72312
The error I get is
attempt to perform arithmetic on global 'test' (a nil value)
This means that test
is nil in the last line. You need to return something in __add
.
Upvotes: 4