# What is Lua++?

Lua++ is a fast, object-oriented programming language derived from Lua 5.1. Its goal is to bring all of today's modern features to Lua while having energy efficiency in mind.

Lua++ is a fully-featured new programming language for a wide range of applications that is fast, lightweight, and energy-efficient. The author created Lua++ with the goal of helping reduce carbon emissions through low power consumption, decreasing barriers to adoption on low-cost hardware platforms, and providing a tool for learning advanced computer science concepts.&#x20;

```typescript
class Triangle {
  base: integer,
  height: integer,
  
  constructor(base: integer, height: integer)
    self.base, self.height = base, height
  end,
  
  const function area(): integer ->
    return self.base * self.height / 2
}

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

Borrowing from several modern languages, Lua++ adds proper object-oriented programming with a class hierarchy and encapsulation, templates, type annotations, events, macros, and much more. Overcoming the limitations of its popular predecessor, Lua++ is suitable for use by teams of developers in large cross-platform projects. The author designed the syntax, built a state-of-the-art optimizing compiler, composed an instruction set, and implemented a fast, compact virtual machine to run Lua++ bytecode in end-user applications. Based on performance tests consisting of several commonly used benchmarks, Lua++ is four to 25 times faster than classic Lua. This documentation gives an overview of the language, discusses rationales for feature choices made, and showcases Lua++’s advantages.


# Why Lua++?

Recognizing the shortcomings and limitations of Lua, the author felt the time was ripe to create Lua++ for general application development. The impetus behind this was threefold:

* **Environmental Impact:** Running on hundreds of millions of computers worldwide, inefficient and slow classic Lua code has an outsized negative impact on the environment. Such scale could be responsible for anywhere between 20 and 90 million tons of carbon dioxide per year ([CarbonDigital](https://sustainablewebdesign.org/calculating-digital-emissions/)). An efficient compiler and virtual machine can get rid of most of those emissions. Low-power hardware devices such as smartwatches and fitness trackers will benefit from a high-level language, without sacrificing battery life.
* **Empowerment:** Low computational requirements will allow use on affordable hardware devices and thereby make advanced programming accessible to historically disadvantaged populations in both developed and developing countries.
* **Educational Opportunities:** In 2020, more than half of American children under the age of 16 played Roblox ([NYTRoblox](https://www.nytimes.com/2020/08/16/technology/roblox-tweens-videogame-coronavirus.html)), a game platform that encourages players to create their own three-dimensional first person games using Lua as a scripting language. Even though writing primitive games in Python and assembling robotics kits are all the rage, chances are that the first language that a child will encounter and relate to will actually be Lua. State-of-the-art programming techniques should be easily available to them at the opportune teaching moment.

As the rest of the paper will demonstrate, Lua++ retains all the benefits of Lua while making it possible to run code close to the speed of today’s fastest programming languages, while drastically improving code maintainability and enabling effective development of large code bases.


# Compound Assignments

When writing programs, it is generally necessary to increment a variable. The problem with Lua and many other high-level scripting languages is that they don’t provide an efficient way to do such a this:

```lua
a = a + 13
```

Although this method is simple and straightforward, it becomes inefficient when dealing with large-scale programs and longer variable names. Additionally, the VM needs to reference the value of `a`, add `13` to it, and update the original value of `a`. An operator for actions like this would decrease execution time and improve developer productivity. The following code block shows an example using the `+=` compound assignment.

```lua
a += 13
```

There is a compound assignment operator for each arithmetic and string operation in Lua, such as (`+=`, `-=`, `/=`, `*=`, `^=`, `%=`, and `..=`). Each operation assigns a variable the value of itself with the operation performed on the original value.


# Postfix and Prefix Operators

Another addition to the Lua++ language is prefix and postfix operators. These can be used to increment and decrement a specific variable within your program. These types of operators are frequently found in C-based programming languages like C++, C#, or Java. The following example demonstrates how to use a postfix increment operator to print numbers from 0 to 9.

```lua
local v: number = 1

while v < 10 do
    print(v)
    v++        -- increment value of v by 1
end
```

The `++` operator will first return the value of that variable and then increment it by 1. If you want to increment the value prior to returning it, you can prefix your variable reference with the `++` operator.

```lua
local v: number = 1
 
print(v++)  -- prints 1
print(++v)  -- prints 2
```

To decrement variables the `---` operator is used which functions exactly like the `++` operator. Lua uses `--` to indicate the beginning of a comment, which conflicts with the conventional `--` decrement operator of many other programming languages. Therefore, Lua++ provides a workaround that disables standard Lua comments using a macro which can be found here: [Comment](/language-improvements/macros/comment).


# The Continue Statement

Another feature shortcoming of Lua is that it lacks the `continue` statement to jump back to the condition of the loop. This statement is essentially the opposite of the `break` statement and a feature that is found in most of today’s most popular programming languages. While the Lua creators have implemented a `goto` statement in more recent versions of Lua it is not as convenient as a `continue`.

```lua
while true do
   continue   -- Make an infinite loop
   print()    -- Never runs
end
```

Also, if continue is used in a `repeat...until` loop, it may not skip the local variable used in the loop condition. Code like this is invalid and will throw an error at compile time:

```lua
repeat
   continue     -- Compiler catches this!
   local a = 1
until a > 0
```


# Constant Variables

Constant variables are variables that are immutable after their first assignment, meaning they can **never** be changed. While they provide no performance benefit, as the compiler will propagate unchanged variables, constant variables are a safety feature for large projects where other developers might not realize that the author meant for the variable not to change. Here is a simple example of constant variables in action:

```lua
const a: number = 12
print(a)

a = 1     -- compiler error!
```

## Constant Functions

Constant functions serve a similar purpose as constant variables do but have a slightly different syntax. If you have a function that performs a specific calculation and you don’t want to create a new one, you can do the following in Lua++:

```typescript
const function add(x, y): number ->
  return x + y
  
print(add(1, 2))
```

With this syntax you are telling the compiler that you don’t need an entirely new environment and that the content of this function can be replaced with all the references in your code. Just like constant variables, the compiler can already identify whether functions like this are defined as constant or not, so from a performance standpoint, it doesn’t matter, but as a developer, this can make your code much cleaner and easier to understand.


# Type Annotations

Unlike any of today’s Lua versions, Lua++ can restrict variables to be of certain type. As projects grow in size, it becomes harder for developers to remember of what type each variable is. Type annotations help prevent insidious bugs that can take hours to discover. In addition, they help enforce interfaces to classes in object-oriented programming.

Lua++ supports five variable primitive types: `boolean`, `string`, `number`, `Table`, and `Array`, which are described in detail in [Broken mention](broken://pages/JRYe5LLCJ1JG5zOfkHNA). To assign a type to a variable, use the `:` separator after the variable name. The annotation can also be used on constant variables. If a variable is assigned a value whose type is not equal to the type of the annotation, then a compiler error will be thrown.

```lua
local a: number = 12
const b: string = "Hello, world!"
```


# Function Annotations

Function annotations serve a similar purpose to type annotations, in that they tell the compiler what type of function to assign to this variable. This can be done either by assigning the type to a local variable or in the function itself.

```lua
local f: (number, string): boolean

-- Valid assignment
f = function(a: number, b: string): boolean
    return true
end
```

The code above demonstrates how to utilize function annotations correctly. Note that primitive types are interchangeable. If the types of functions are not identical to the definition, then the compiler will throw an exception. Below is another example of how to annotate a function with types:

```lua
local function f(a: number, b: number): boolean
    return a == b
end

-- Error: should return boolean not string
local function g(x: number): boolean
    return "Hello"
end
```


# 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
}
```

<table><thead><tr><th width="248">Token</th><th>Description</th></tr></thead><tbody><tr><td>tag</td><td>The type name given to the class.</td></tr><tr><td>template-spec</td><td>Optional template specifications.</td></tr><tr><td>base-list</td><td>Optional list of classes this class will derive members from.</td></tr><tr><td>member-list</td><td>List of members.</td></tr></tbody></table>

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

```typescript
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:

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


# Constructors

Lua++ supports two different kinds of constructors by default: `implicit` and `explicit`. Explicit constructors require the parameters to be wrapped in parentheses, while `implicit` allow the value to be directly passed as shown in the following examples:

```typescript
class ExplicitConstructor {
    value: number,

    constructor(value: number)
        self.value = value
    end
}

local exp: ExplicitConstructor = ExplicitConstructor(1)
```

```typescript
class ImplicitConstructor {
    value: number,

    implicit constructor(value: number)
        self.value = value
    end
}

local imp: ImplicitConstructor = 1
```


# Templating

Class templating is a feature commonly found in type-oriented programming languages like TypeScript or C++. While class templating is sometimes seen as having limited applications, it allows the creation of type-flexible classes that significantly reduces repetitive code.

Templating in Lua++ is quite simple and efficient. It works like so: `tag` where `T` is a type. To allow more than one type, one would separate each type name with a comma, such as: `tag<T1, T2, ...>`. A simple example of templating is shown below:

```typescript
class Pair<T1, T2> {
  first: T1,
  second: T2,
  
  implicit constructor(f: T1, s: T2)
    self.first, self.second = f, s
  end
}

local pair: Pair<number, string> = { 3, "Three" }
```


# Inheritance

Like all object-oriented programming languages, Lua++ supports full class inheritance. To inherit all the heritable properties of a class in Lua++, one would separate the class name from the base class using a colon in this way: `tag : base-class`, and for multiple class inheritance, one would separate each base class with a comma: `tag: base-1, base-2, ...` as shown in the following example:

```typescript
class Person {
    firstName: string,
    lastName:  string,

    constructor(firstName: string, lastName: string)
        self.firstName = firstName
        self.lastName = lastName
    end,

    function getName(): string
        return self.firstName .. " " .. self.lastName
    end,

    function getDescription(): string
        return "This is " .. self.getName() .. "."
    end
}
```

Here we define a base class `Person`, with the `firstName` and `lastName` properties. This class has two public methods, `getName()`, and `getDescription()`. As mentioned earlier, to inherit a class you use the `:` operator. For example, the following `Employee` class inherits properties and methods from the `Person` class:

```typescript
class Employee : Person { 
    
}
```

Since the `Person` class has a constructor that initializes the `firstName` and `lastName` properties, you need to initialize these properties in the constructor of the `Employee` class by calling its parent class’ constructor. This can be done by using the `base()` keyword.

```typescript
class Employee : Person {
    job: string,    
 
    constructor(firstName: string, lastName: string, 
                job: string)
        self.job = job
        
        -- Call the constructor of the person class
        base(firstName, lastName)
    end
}
```

The following creates an instance of the `Employee` class which inherits all the methods and properties of the `Employee` class:

```lua
local employee: Employee = Employee("Max", "Prihodko", "Programmer")
```

Lua++ also allows you to override methods inherited by a base class. This can be done by using the `:` symbol after the name definition of the class.

```typescript
class Employee : Person {
    job: string,    
 
    constructor(firstName: string, lastName: string,
                job: string)
        self.job = job
        
        -- Call the constructor of the person class
        base(firstName, lastName)
    end,

    function describe(): string
        return base.describe() .. " I am a " .. 
                                    self.job .. "."
    end
}

local employee: Employee = Employee("Max", "Prihodko",
                                    "Programmer")

print(employee.describe())
```

The output of this fragment of code will be:

```
This is Max Prihodko. I am a Programmer.
```


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


# Events

The event keyword is used to declare an event in a publisher class. The following code segment displays how to declare and raise an event.

```typescript
class Publisher {
    event SampleEvent: (sender: any, text: string),

    function RaiseSampleEvent(text: string)
        SampleEvent.Invoke(self, text)
    end
}
```

Events can only be invoked from within a class, so they can be extremely useful when implementing a customizable API or library. One can assign a function to be called whenever the publisher class raises the event by doing the following:

```typescript
function OnInvoked(sender, text: string)
  print("SampleEvent has been invoked!")
end

local publisher: Publisher = Publisher()

publisher.SampleEvent += OnInvoked
```


# Macros

Macros are commands within the code that allow for customization of the Lua++ compiler’s behavior. To use a macro one would use the `--!` prefix followed by the name of the macro. These macros must be the first statement of the program. Otherwise, the compiler will throw an error. Here are some examples:

```lua
--!<macro>
print("hello")
```

The following segment will not compile successfully as there is a statement preceding the macro definition:

```lua
local v = 1 -- NO
--!<macro>
print("hello")
```


# Lenient

Developers simply interested in using the Lua++ compiler can use `--!lenient` to disable the strict type checker. Although using this macro is strongly discouraged as it will make code management much more difficult, it could be helpful when looking to compile basic Lua scripts that can be run on the Lua++ VM.

```lua
--!lenient

local v = 100     -- no error because macro is defined
print(v)
```


# Comment

As mentioned in the postfix section, traditional Lua comments prevent the implementation of the decrementation operator (`--`). To disable the traditional single-line Lua comment, one can use `--!comment`. Once the compiler sees that this macro is specified, single-line comments will transition over to the `#` sign and the `--` operator will replace `---` for decrementation.

Below is a code segment that would yield an error at compilation after applying the `--!comment` macro.

```lua
--!comment

-- this is an invalid comment (and code)
local v = 1
print(v---)
```

The following code segment demonstrates the correct usage of the `--!comment` macro and the syntax change it produces.

```lua
--!comment

# Valid new comment
local v = 1
print(v--)
```

An alternative to this approach of managing the conflicting comment and decrement operator issue would be to use reassignments (`var = var - 1`) or compound assignments (`var -= 1`).


# C-Arrays

A rather new addition is the `--!carrays` macro. This macro forces the first element in arrays to start at `0` not `1` like usual. This macro was added for all those C-style programmers (and others) who can't stand this feature about Lua. The following code segment shows this macro in action:

```lua
--!carrays

local array: Array<number> = { 1, 2, 3 }

print(array[0])    -- Gets first element (1)
print(array[1])    -- Gets second element (2)
```


# Installing the Project

Just like any open-source software, we are open to contributors and would love to have some extra helping hands! This section will go over how to correctly install the Lua++ project so that you can become a contributor.

<details>

<summary><mark style="color:blue;">Step 1:</mark>  Forking the Repository</summary>

The first and most important part of this process is forking your desired repository. There are a few steps to this process:

1. On GitHub.com, navigate to the [luapp-org/luapp](https://github.com/luapp-org/luapp) repository.

2. In the top right corner of the page, click **Fork.**<br>

   <figure><img src="https://3830794175-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4UivSLxpywEEiaOp1OMZ%2Fuploads%2FLXmuv3MslCcalqIrx8ah%2Fimage.png?alt=media&amp;token=0cea7a29-f1a8-46d2-9af4-a734891c039f" alt=""><figcaption><p>The <strong>Fork</strong> button at the top right of the page</p></figcaption></figure>

3. Once you have forked the repository, you need to clone the repo to your local machine so that you can add your changes. You can find the link to the repo after clicking the **Code** dropdown.<br>

   <figure><img src="https://3830794175-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4UivSLxpywEEiaOp1OMZ%2Fuploads%2FFh4eP457s6zGin0RV9rQ%2Fimage.png?alt=media&amp;token=c70addc9-d0fb-4228-ad15-7e9674d5fc21" alt=""><figcaption><p>The <strong>Clone</strong> menu for the repo.</p></figcaption></figure>

   Then run the clone command in your local environment:\
   `git clone <link>`

&#x20;

</details>

Before you can get to contributing you need to install Lua++'s few dependencies. Instructions are listed below in the order of your operating system.

{% tabs %}
{% tab title="Linux" %}
You need to install `make`, `flex`, and `bison`. To install them on a Linux machine run the following commands:

```
sudo apt update
sudo apt install flex
sudo apt install bison
sudo apt install make
```

Then you need to enter the main source folder and build the desired project (e.g. `make interpreter`). The binaries are stored in `src/bin` with `luappc` being the compiler, `luappvm` the VM, and `luapp` the interpreter.
{% endtab %}
{% endtabs %}

<details>

<summary><mark style="color:blue;">Step 2:</mark>  Creating a Pull Request</summary>

1. To begin committing new changes to your fork, you need to first create a new branch. This can be done with the following command:\
   `git checkout -b new-user-contribution`
2. Once you have committed your changes to your new branch, you need to **create a pull request**.<br>

   <figure><img src="https://3830794175-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4UivSLxpywEEiaOp1OMZ%2Fuploads%2FgEtA7CR7SgbeGIOj3OqH%2F3hgusjnp9c93g9zt3o72.png?alt=media&amp;token=82e4d405-9339-4944-92d4-ffedb827df37" alt=""><figcaption><p>How to create a new pull request.</p></figcaption></figure>

</details>

Thank you for showing interest Lua++, we hope that we can get as much assistance from the community as possible. Happy coding!&#x20;


