Documentation
GitHubTwitter
  • overview
    • What is Lua++?
    • Why Lua++?
  • language improvements
    • Compound Assignments
    • Postfix and Prefix Operators
    • The Continue Statement
    • Constant Variables
    • Type Annotations
      • Function Annotations
    • Classes
      • Constructors
      • Templating
      • Inheritance
      • Encapsulation
    • Events
    • Macros
      • Lenient
      • Comment
      • C-Arrays
  • contributing
    • Installing the Project
Powered by GitBook
On this page

Was this helpful?

  1. language improvements
  2. Classes

Encapsulation

One of the biggest problems with Lua’s simulated OOP is that it does not provide a safe method of limiting access to member variables and methods. One can't create "black-box" style interfaces to classes and libraries to prevent other programmers from modifying things they shouldn't. In Lua++ all members of a class are public by default, but they can be hidden from being accessed from anywhere but within the class using the private keyword.

class Person {
    -- This variable can't be accessed outside the class
    private age: number,
    
    constructor(age: number)
        self.age = age
    end,

    function getAge(): string
        return "This person is " .. age .. " years old."
    end
}

local p: Person = Person(100)
print(p.getAge())  -- OK
print(p.age)       -- Error, since age is private

Class methods can also be made private to hide those that should only be called internally by other class functions.

PreviousInheritanceNextEvents

Last updated 2 years ago

Was this helpful?