CSci 450/503: Programming Languages
Lua Objects

H. Conrad Cunningham

17 October 2016

Acknowledgements: These slides are adapted from slide set 11 for the course Programming in Lua created by Fabio Mascarenhas, Federal University of Rio de Janeiro, Brazil. It was presented at Nankai University, P. R. China, in July 2013.

Advisory: The HTML version of this document may require use of a browser that supports the display of MathML. A good choice as of October 2016 is a recent version of Firefox from Mozilla.

LUA OBJECTS

Lua Objects

Methods

Methods and :

Declaring Methods

Square Object

    local square = { x = 10, y = 20, side = 25 } 

    function square:move(dx, dy) 
       self.x = self.x + dx
       self.y = self.y + dy 
    end

    function square:area() 
       return self.side * self.side 
    end
    
    return square
       
    > print(square:area())
    625
    > square:move(10, -5) 
    > print(square.x, square.y) 
    20      15 

Classes

Square Class as Module

    local Square = {} 
    Square.__index = Square

    function Square:new(x, y, side) 
       return setmetatable({ x = x, y = y, side = side }, self) 
    end 

    function Square:move(dx, dy) 
       self.x = self.x + dx 
       self.y = self.y + dy 
    end                               > s1 = Square:new(10, 5, 10)
                                      > s2 = Square:new(20, 10, 25) 
    function Square:area()            > print(s1:area(), s2:area()) 
       return self.side * self.side   100     625 
    end                               > s1:move(5, 10) 
                                      > print(s1.x, s1.y) 
    return Square                     15      15 

Default Fields

Circle Class

    local Circle = {} 
    Circle.__index = Circle

    function Circle:new(x, y, radius) 
       return setmetatable({ x = x, y = y, radius = radius }, self) 
    end 

    function Circle:move(dx, dy) -- same as for Square
       self.x = self.x + dx 
       self.y = self.y + dy 
    end 

    function Circle:area() 
       return math.pi * self.radius * self.radius 
    end 

   return Circle 

Shape Superclass

Point extends Shape

Circle extends Shape

Other Object Models

Quiz

instanceof Function

Assuming the object/class model from this set of slides:

    function instanceof(obj, class)
       local mt = getmetatable(obj) -- get class prototype
       if mt == class then          -- is instance of class?
          return true
       elseif mt == nil then        -- top has no metatable
          return false 
       else                         -- check superclass
          return instanceof(mt, class) 
       end
    end