1

I'm trying to run the following in Lua 5.3

function new_t()
  local self = {}
  setmetatable(self, {
    __add = function(lhs,rhs)
        print('ok so',lhs,'+',rhs)
    end
  })
  return self 
end

local t1 = new_t()
local t2 = new_t()

t1 + t2

I get an error saying syntax error near '+'. However if I change the last line to x = t1 + t2, it runs and prints without error.

Is it possible to use a binary operator without using the resulting value? Why doesn't Lua let me do t1 + t2 or even 1 + 2 by itself?

4
  • Just got done writing my answer, and I got curious: Do you really intend to print something in __add, or is that some kind of temporary testing thing? Commented Jun 5, 2021 at 21:39
  • @luther temporary testing! I'd like to use this addition operation as just a convenient way to modify the lhs table. For instance, instead of t1:add(t2), I want to try t1 + t2. Commented Jun 5, 2021 at 21:49
  • I should've asked that to begin with. I've edited my answer. Commented Jun 5, 2021 at 22:03
  • You could do print( t1 + t2 ) or t1 = t1 + t2 Commented Jun 5, 2021 at 23:03

1 Answer 1

1

Lua doesn't allow this, because all the operators (except function calls) are intended to always calculate a result. There's no good reason to throw away the result of an expression, and it usually indicates a coding mistake.

If you just want to test your code, I suggest using assert:

assert(not (t1 + t2))

I use not here, because your __add function doesn't return anything.

EDIT: Normally, when we add two numbers, we expect to get a new number, without changing the original numbers. Lua's metamethods are designed to work the same way. To do side-effects like printing or modifying an operand, it's easier and clearer to use a regular named method.

Sign up to request clarification or add additional context in comments.

1 Comment

local _ = t1 + t2 would be better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.