Toast
Toast

Reputation: 13

Using addition in Lua without using the result

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?

Upvotes: 1

Views: 289

Answers (1)

luther
luther

Reputation: 5554

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.

Upvotes: 1

Related Questions