Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs

TIC-80

tiny computer for making, playing and sharing tiny games · By Nesbox

Operator Overloading

A topic by OlivierSchyns created Apr 10, 2017 Views: 275
Viewing posts 1 to 1
(1 edit)

I just discovered that lua support operator overloading for tables so I had to test it out.

So i tried in TIC-80 and it works, so I though "What about moonscript ?'

It happens that it is that easy:

-- example of the use of lua's metamethods with moonscript's classes
class Vector
  
  new:(x,y)=>
    @x = x
    @y = y
  
  __add:(vecA,vecB)->
    return Vector(vecA.x + vecB.x, vecA.y + vecB.y)


a = Vector 1,2
b = Vector 3,4

c = a + b

print "c.x = "..c.x -- prints 4 (1+3 = 4)
print "c.y = "..c.y -- prints 6 (2+4 = 6)

So it is possible to change the behavior of operators based on the class of the tables.

If other people are interrested, you can read the lua doc regarding metamethods.

LUA's metamethods