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.

Last updated