Search code examples
oopluametatable

Lua complex number class arithmetic


I have some lua code implemented with the standard binary operators ==,>,<,-,+,*,etc. I want to add some functionality with a lua object like imaginary numbers (not specifically imaginary numbers, but an answer with them in mind would still be exactly what I'm looking for). I want the original operators throughout the code to function without having to replace each instance of one of these operators with a function like mult(x,y) that would consider the case of a number being imaginary. In Python, one would use

__add__,__mul__,etc.

(see here if unfamiliar) I am looking for an analog in lua. Could I get a suggested class structure with this functionality in mind?


Solution

  • You can read the theory here: Metatables
    And here is an example of complex numbers implementation. I can paste some code from that example

    -- complex.add( cx1, cx2 )
    -- add two numbers; cx1 + cx2
    function complex.add( cx1,cx2 )
       return setmetatable( { cx1[1]+cx2[1], cx1[2]+cx2[2] }, complex_meta )
    end
    
    -- complex.sub( cx1, cx2 )
    -- subtract two numbers; cx1 - cx2
    function complex.sub( cx1,cx2 )
       return setmetatable( { cx1[1]-cx2[1], cx1[2]-cx2[2] }, complex_meta )
    end
    
    --// metatable functions
    complex_meta.__add = function( cx1,cx2 )
       local cx1,cx2 = complex.to( cx1 ),complex.to( cx2 )
       return complex.add( cx1,cx2 )
    end
    complex_meta.__sub = function( cx1,cx2 )
       local cx1,cx2 = complex.to( cx1 ),complex.to( cx2 )
       return complex.sub( cx1,cx2 )
    end