Classes

Lua++ has been designed to support real object-oriented programming by implementing classes. They function similarly to Lua tables but eliminate the need for simulated solutions using metamethods. Classes in Lua++ have similar syntax and behaviors to those in TypeScript and are structured like so:

class [tag [template-spec] : [base-list]] {
  member-list
}
Token
Description

tag

The type name given to the class.

template-spec

Optional template specifications.

base-list

Optional list of classes this class will derive members from.

member-list

List of members.

To demonstrate just how superior classes are to the legacy tables, consider code fragments that calculate the area of a triangle.

class Triangle {
  b: number,
  h: number,
  
  constructor(b: number, h: number)
    self.b, self.h = b, h
  end,
  
  const function area(): number ->
    return (self.b * self.h) / 2.0
}

print(Triangle(3, 4).area())

Contrast code above with the following implementation in classic Lua:

local Triangle = { width = 0, height = 0 }
 
function Triangle:set( fWidth, fHeight )
    self.width = fWidth
    self.height = fHeight
end
 
function Triangle:get()
    return { 
       width = self.width, 
       height = self.height 
    }
end
 
function Triangle:area()
    return self.width * self.height / 2.0
end

Triangle:set(100, 300)
print(Triangle:area())

As illustrated, Lua++ classes provide a simple and straightforward interface for getting and setting member variables while Lua’s tables perform a similar function but are awkward and inconvenient.

Last updated