> For the complete documentation index, see [llms.txt](https://docs.luaplusplus.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.luaplusplus.org/language-improvements/classes/encapsulation.md).

# 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.

```lua
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.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.luaplusplus.org/language-improvements/classes/encapsulation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
