# 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
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.otland.net/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Introduction

## Guide to setting up and maintaining an Open Tibia server

This book will cover the basics of setting up your first Open Tibia server, introduce you to its interface, teach you some scripting, and more.

## What is Open Tibia?

Open Tibia (abbreviated as OT) is an open source role-playing game that allows people to create their own servers for the public to play. They may have unique content, brand-new maps, special features or even custom skill/level rates different than those in the original Tibia.

Along with Open Tibia comes an Open Tibia community formed by players just like you who want to create something of their own. People within this community help each other, provide tutorials, contribute to the development of new and improved servers, among other things.


# Compiling

Instructions for compiling TFS from source.

TFS is able to be compiled on different Operating Systems. This section contains pages with instructions for those different Operating Systems.

You can also find most up-to-date instructions in TFS's [wiki](https://github.com/otland/forgottenserver/wiki).


# Compile on Arch

**1. Install the required software**

The following command will install Git, CMake, a compiler and the libraries used by The Forgotten Server.

Git will be used to download the source code, and CMake will be used to generate the build files.

```
$ sudo pacman -Syu
$ sudo pacman -S base-devel git cmake luajit boost boost-libs libmariadbclient pugixml crypto++ fmt
```

**2. Download the source code**

```
$ git clone https://github.com/otland/forgottenserver.git
```

**3. Generate the build files**

```
$ cd forgottenserver
$ cmake . -B build
```

**4. Build**

```
$ make -C build
```

The executable will be located in `./build/tfs`


# Compiling on CentOS

### CentOS 8

**Enable PowerTools to install lua-devel**

```
$ sudo sed -i 's/enabled=0/enabled=1/g' /etc/yum.repos.d/CentOS-PowerTools.repo
```

**Install this package to get pugixml-devel**

```
$ sudo dnf install epel-release  # for luajit pugixml-devel cryptopp-devel
$ sudo dnf install git boost-devel make cmake3 cryptopp-devel gcc-c++ gmp-devel lua-devel luajit mariadb-devel pugixml-devel fmt
```

**2. Download the source code**

```
$ git clone https://github.com/otland/forgottenserver.git
```

**3. Generate the build files**

```
$ cd forgottenserver
$ mkdir build && cd build
$ cmake ..
```

**4. Build**

```
$ make
```

Note: If you're getting an error with text "had text segment at different address", try running the following command and repeat steps 3 & 4 again:

> sed -i "s/-Werror//g" ../CMakeLists.txt

### CentOS 7

**1. Install the required software**

The following command will install Git, CMake, a compiler and the libraries used by The Forgotten Server.

Git will be used to download the source code, and CMake will be used to generate the build files.

```
$ sudo yum install epel-release  # for cmake3 luajit pugixml-devel
$ sudo yum install git boost-devel cmake3 cryptopp-devel gcc-c++ gmp-devel lua-devel luajit mariadb-devel pugixml-devel
```

**2. Download the source code**

```
$ git clone https://github.com/otland/forgottenserver.git
```

**3. Generate the build files**

```
$ cd forgottenserver
$ mkdir build && cd build
$ cmake3 ..
```

**4. Build**

```
$ make
```


# Compiling on Debian GNU Linux

The Forgotten Server requires at least gcc 5.0, which is available in Debian 9.

**1. Install the required software**

The following command will install Git, CMake, a compiler and the libraries used by The Forgotten Server.

Git will be used to download the source code, and CMake will be used to generate the build files.

```
# apt-get install git cmake build-essential libluajit-5.1-dev libmariadb-dev-compat libboost-date-time-dev libboost-filesystem-dev libboost-system-dev libboost-iostreams-dev libpugixml-dev libcrypto++-dev libfmt-dev
```

Replace `libmariadb-dev-compat` with `libmysqlclient-dev` on Debian 8 and below.

**2. Download the source code**

```
$ git clone --recursive https://github.com/otland/forgottenserver.git
```

**3. Generate the build files**

```
$ cd forgottenserver
$ mkdir build && cd build
$ cmake ..
```

**4. Build**

```
$ make
```


# Compiling on Fedora

**1. Install the required software**

The following command will install Git, CMake, a compiler and the libraries used by The Forgotten Server.

Git will be used to download the source code, and CMake will be used to generate the build files.

```
$ sudo dnf install git cmake gcc-c++ boost-devel community-mysql-devel lua-devel pugixml-devel cryptopp-devel make fmt-devel
```

**2. Download the source code**

```
$ git clone --recursive https://github.com/otland/forgottenserver.git
```

**3. Generate the build files**

```
$ cd forgottenserver
$ mkdir build && cd build
$ cmake ..
```

**4. Build**

```
$ make
```


# Compiling on FreeBSD

**1. Install the required software**

The following command will install Git, CMake and the libraries used by The Forgotten Server.

Git will be used to download the source code, and CMake will be used to generate the build files.

```
# pkg install git cmake luajit boost-libs gmp mysql-connector-c pugixml
```

**2. Download the source code**

```
$ git clone --recursive https://github.com/otland/forgottenserver.git
```

**3. Generate the build files**

```
$ cd forgottenserver
$ mkdir build && cd build
$ cmake ..
```

**4. Build**

```
$ make
```


# Compiling on Gentoo

**1. Install the required software**

The following command will install Git, CMake and the libraries used by The Forgotten Server.

Git will be used to download the source code, and CMake will be used to generate the build files.

```
# emerge dev-vcs/git dev-util/cmake dev-libs/boost dev-db/mysql-connector-c++ dev-lang/luajit dev-libs/pugixml
```

**2. Download the source code**

```
$ git clone --recursive https://github.com/otland/forgottenserver.git
```

**3. Generate the build files**

```
$ cd forgottenserver
$ mkdir build && cd build
$ cmake ..
```

**4. Build**

```
$ make
```


# Compiling on Mac OS X

**1. Install the required software**

**1.1. Installing Homebrew**

Homebrew is a package manager for Mac OS X. It uses formulae scripts to compile the software on your system. If you already have Homebrew installed, you can skip this step.

Open a Terminal window and run:

```
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```

**1.2. Installing software and libraries**

The following command will install Git, CMake and the libraries used by The Forgotten Server.

Git will be used to download the source code, and CMake will be used to generate the build files.

```
$ brew install git cmake gmp mysql-connector-c luajit boost pugixml pkg-config fmt
```

Install [cryptopp](https://github.com/weidai11/cryptopp) manually (it is no longer available via brew). Make sure to use latest version, in case it is 8.5.0, you can try this:

```
wget https://github.com/weidai11/cryptopp/archive/refs/tags/CRYPTOPP_8_5_0.zip
unzip CRYPTOPP_8_5_0.zip && cd cryptopp-CRYPTOPP_8_5_0
make shared all
make install
```

**2. Download the source code**

```
$ git clone --recursive https://github.com/otland/forgottenserver.git
```

**3. Generate the build files**

```
$ cd forgottenserver
$ mkdir build; cd build
$ cmake ..
```

**4. Build**

```
$ make
```


# Compiling on Ubuntu

In order to compile The Forgotten Server under Ubuntu, you need Ubuntu 24.04 at least due to package requirements. Then follow the next steps:

**1. Install the required software**

The following command will install Git, CMake, a compiler and the libraries used by The Forgotten Server.

Git will be used to download the source code, and CMake will be used to generate the build files.

```
sudo apt install git cmake build-essential libluajit-5.1-dev libmysqlclient-dev libboost-system-dev libboost-iostreams-dev libpugixml-dev libcrypto++-dev libfmt-dev libboost-locale-dev libboost-json-dev liblua5.3-dev
```

**2. Download the source code**

```
git clone --recursive https://github.com/otland/forgottenserver.git
```

**3. Generate the build files**

```
cd forgottenserver
mkdir build && cd build
cmake ..
```

**4. Build**

```
make
```


# Compiling on Windows

> Note: since 2018-06-17 the `theforgottenserver.sln` MSVS project file is no longer configured for use with TFS SDK. Please follow \[\[Compiling on Windows (with vcpkg)|Compiling-on-Windows-(vcpkg)]] instead. The following tutorial applies to all versions until and including TFS 1.2 and master branch until commit bcb86ea.

***

**1. Download the required software**

To compile The Forgotten Server on Windows, you will need:

* [Visual Studio 2017 Community](https://www.visualstudio.com/) (compiler)
* [TFS SDK v3.2](https://static.otland.net/dl/tfs-sdk-3.2.zip) (libraries)
  * sha1sum: 3fb1b140e40e8e8bc90f82f92bd022a50569b185
  * sha256sum: 2ffb549f336ad11550da9b9c40716880e13b1cc0ee86e7599022dcacc972a3bf
* Boost C++ libraries for MSVC 14.1 ([32-bit download](https://sourceforge.net/projects/boost/files/boost-binaries/1.66.0/boost_1_66_0-msvc-14.1-32.exe/download), [64-bit download](https://sourceforge.net/projects/boost/files/boost-binaries/1.66.0/boost_1_66_0-msvc-14.1-64.exe/download))

Note: Up until TFS 1.2 OR in master branch until 2017-12-31 you need the following instead:

* [Visual Studio 2015 Community](https://www.visualstudio.com/) (compiler)
* Boost C++ libraries for MSVC 14.0 ([32-bit download](https://sourceforge.net/projects/boost/files/boost-binaries/1.62.0/boost_1_62_0-msvc-14.0-32.exe/download), [64-bit download](https://sourceforge.net/projects/boost/files/boost-binaries/1.62.0/boost_1_62_0-msvc-14.0-64.exe/download))

**2. Install the required software**

Once you have downloaded the software listed in the step above, begin by installing Visual Studio and Boost C++ libraries. Extract TFS SDK anywhere on your computer and run the file "register\_tfssdk\_env.bat" to set the PATH environment variable for TFS SDK, so that the compiler can find the libraries once we get to compiling the source code. Move the file "register\_boost\_env.bat" from TFS SDK to the directory where you installed Boost C++ libraries and run it there (it should be in the directory called boost\_1\_62\_0).

**3. Download the source code**

If you have a Git client installed, you can clone the latest copy with this command:

```
git clone --recursive https://github.com/otland/forgottenserver.git
```

If you don't have a Git client installed, you can download the latest copy of The Forgotten Server from this URL: <https://github.com/otland/forgottenserver/archive/master.zip>

**4. Build**

Find the directory vc14 in the copy of The Forgotten Server that you downloaded, and open theforgottenserver.sln. This should launch Visual Studio, and you should be good to go.

To configure the build, navigate to Build -> Configuration Manager in the menu. A dialog should pop up where you can choose between Release or Debug build, and 32-bit (Win32) or 64-bit (x64) build.

To start compiling, open the Build menu again and click on Build Solution.


# Compiling on Windows (vcpkg)

**1. Download/install the required software**

To compile on Windows, you will need to download and install:

* [Git](https://git-scm.com/download/win)
* [Visual Studio 2022 Community](https://visualstudio.microsoft.com/vs/) (compiler, make sure to install with the English language pack)
* [vcpkg](https://github.com/Microsoft/vcpkg) (package manager)

**2. Set up vcpkg**

Make sure to follow full installation of vcpkg, per [Official Quickstart](https://github.com/Microsoft/vcpkg#quick-start) execute the following in *cmd* or *Powershell*:

To open Powershell navigate to your desired directory and choose `Open PowerShell window here` (shift + right click).

If you prefer `cmd` (command prompt) click on your `Start` windows button or just use the windows key on your keyboard and search for `cmd` then navigate to your desired directory using `cd` e.g. you want to have your vcpkg folder on root of your C drive:

```
cd C:\
```

then you can safely proceed with configuring vcpkg (may require administrator elevation)

```
git clone https://github.com/Microsoft/vcpkg && cd vcpkg && .\bootstrap-vcpkg.bat && .\vcpkg integrate install
```

**3. Download the source code**

```
git clone --recursive https://github.com/otland/forgottenserver.git
```

**4. Install libraries**

Choose one set of libraries, depending on the target platform and execute the following in *Git Bash* or *Powershell*:

Note: **boost-filesystem** is not needed from [4b800b2](https://github.com/otland/forgottenserver/commit/4b800b20558f24344c5024fb3cb9a4974ebad90e) onwards

* For 64-bit (x64) build:

  ```
  .\vcpkg install --triplet x64-windows boost-iostreams boost-asio boost-system boost-filesystem boost-variant boost-lockfree luajit libmariadb pugixml cryptopp fmt
  ```
* For 32-bit (Win32) build:

  ```
  .\vcpkg install boost-iostreams boost-asio boost-system boost-filesystem boost-variant boost-lockfree luajit libmariadb pugixml cryptopp fmt
  ```

**5. Build**

1. **Open `vc17/theforgottenserver.vcxproj`**. This should launch Visual Studio.
2. Choose build configuration from the drop downs (Debug or Release and Win32 or x64). For best performance choose Release & x64.
3. To start compiling **press F7**.


# Running your first OT Server


# Setting up your first server

When setting up your first server, things may seem quite tedious to look at, but it will certainly get easier as we go.

**Installing a text editor**

When editing code, programmers tend to use certain text editors they are most familiar with. This lets them program easierly thanks to features like highlighting, auto-complete, etc. The most popular text editors are [Notepad++](https://notepad-plus-plus.org/download) (free) and [Sublime Text](https://www.sublimetext.com/3) (free trial). You may install whichever one appeals more to you, as we will be using it later on.

**Database**

Open Tibia servers store information such as accounts, players, house items and many more things in a database. This database is a separate service from the Open Tibia server itself, but it is necessary for the server to work. This means you need to install a database service to run alongside the Open Tibia server. In this tutorial, we will be using [Uniform Server Zero](http://www.uniformserver.com/) (stable version: [13\_3\_2\_ZeroXIII.exe](https://sourceforge.net/projects/miniserver/files/Uniform%20Server%20ZeroXIII/13_3_2_ZeroXIII/13_3_2_ZeroXIII.exe/download)), a web server which includes a database service (MySQL) and a web based database management tool called phpMyAdmin, where you will be able to view and modify data such as player names, levels or other stored information.

After downloading Uniform Server Zero, extract it and open "unicontroller.exe". If you come across any errors, you may need to install [vc\_redist.x64.exe](https://aka.ms/vs/16/release/vc_redist.x64.exe). Otherwise, a prompt will ask you to change your MySQL root password. It is highly recommended to do so, as leaving the default password may be risky.

Now you can start Apache and MySQL by just clicking the buttons on the new window that will appear. Two webs will pop up, you may close them. It's time to open "phpMyAdmin" by clicking on the button. A new window should pop up in your default browser.

The website you're looking (phpMyAdmin) will allow you to modify the information in MySQL easily. First things first, we are going to create our databse and import our schema from TFS:

1. On the left sidebar, click "New".
2. Select your database name and click "Create".
3. Your database should be created now and selected.
4. At the top, click the "Import" button.
5. Click "Choose File" next to "Browse your computer" and locate the "schema.sql" file from TFS sources.
6. Scroll down and click "Go".

The database is ready to go! Our server will now be able to store and retrieve information from it.

**Server files**

You will need a set of files before you can run your server. The files can be found [here](https://github.com/otland/forgottenserver/releases/tag/v1.2). Once downloaded, extract the zip. You will also need another set of files which are required to run the server engine, you can find them [here](https://otland.net/threads/opentibia-dll-pack-v2-0.155310/). Extract them into the same folder as beore.

The folder should look like this now:

![](https://995696672-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVBMVPm-MlN4K7ZoPJo%2F-LnITgTT-13iJpSSE10p%2F-LnJAsfWrcwj8Tc3o_aw%2Fimage.png?alt=media\&token=7816dc71-09be-42e5-aad0-f3fb1f7c97aa)

Open config.lua with your preferred text editor and follow these steps:

1. Locate mysqlUser and change the value to "root", if necessary.
2. Locate mysqlPass and change the value to the one you selected earlier.
3. Locate mysqlDatabase and change the value to the one you chose in the second step of the previous section.

Once you are done, save and close the file.

Now it's time for you to open theforgottenserver.exe... Your server is now running!

**Website (Znote AAC)**

To create an account on your new server, we will need to set up a website. We will be using Znote AAC for this tutorial, which you can get [here](https://github.com/znote/znoteaac).

Extract the .zip file to your web directory (for example, "C:\UniServZ\www"), which should be empty. Enter the website (if your web directory is UniServZ's, you can do this by clicking "View www" in unicontroller) and wait for MySQL connection error. This will show you the rest of the instructions:

1. The first step is the one we already did when setting up the database.
2. The second step tells you to run the given SQL queries in your database via phpMyAdmin.
3. The third step asks you to modify config.php. Open it with your text editor and edit the following variables (at least):
   1. `$config['ServerEngine']` with the correct TFS version you are running (`TFS_02`, `TFS_03` or `TFS_10`).
   2. `$config['sqlUser']` with your MySQL user (root).
   3. `$config['sqlPassword']` with the MySQL password you chose.
   4. `$config['sqlDatabase']` with the database name you chose.

You should now be able to connect to your website by typing to 127.0.0.1, localhost or your IP in your browser. Go ahead and create your account and character!

**Website alternative (Gesior AAC)**

Download Gesior 2012 from GitHub: <https://github.com/gesior/Gesior2012/archive/TFS-1.0.zip>

Extract the .zip file to your web directory (for example, "C:\UniServZ\www"), which should be empty. Enter the website (if your web directory is UniServZ's, you can do this by clicking "View www" in unicontroller) and follow the installation steps. In case you come across an error in step 2, add this line somewhere in your config.lua: `passwordType = "sha1"`.

You should now be able to connect to your website by typing to 127.0.0.1, localhost or your IP in your browser. Go ahead and create your account and character!


# Connecting to your server

**Connecting with Tibia native client**

In order to connect to your server, you will need [OtLand IP Changer](https://otland.net/threads/otland-ip-changer.134369/). This tool lets you change the IP address of your Tibia client, so that you can connect to the server when entering your account name and password to log in.

The first thing to do after downloading and opening it is to go to Settings, click on "Add new Tibia client", set the version and select the Tibia client executable file. Finally, click the "Add" button.

Close the settings windows and enter 127.0.0.1 in the IP field, select the client version and click "Apply".

The client should start automatically and you should be able to log in using your account name and password, if you have already created one using the website we set up previously.

**OTClient**

If you wish, you can alternatively use OTClient to connect to your server, this way you won't need any IP changer. If you are running Windows, you can find the latest builds for Windows here: <https://otland.net/threads/otclient-builds-windows.217977/>. Please note that it might not be the latest version, if you wish to use the latest version, you will have to compile your own. To do that, you can follow these guides:

* Android: <https://github.com/edubart/otclient/wiki/Compiling-for-Android>
* Linux: <https://github.com/edubart/otclient/wiki/Compiling-on-Linux>
* Mac OS X: <https://github.com/edubart/otclient/wiki/Compiling-on-Mac-OS-X>
* Windows: <https://github.com/edubart/otclient/wiki/Compiling-on-Windows>
* The source code can be found here: <https://github.com/edubart/otclient/archive/master.zip>


# Editing your datapack

### What are the languages used

There are two main languages used when working with TFS: XML and Lua. Depending on your knowledge, you may also want to edit the sources, which would mean you would have to work with C++ as well. XML is a markup language that lets you register Lua scripts and store information, while Lua is used for scripting and interacting with the game world. You can start learning Lua with [Programming in Lua](https://www.lua.org/pil/contents.html) or [Stigma's Lua guide](https://stigmax.gitbook.io/lua-guide/).

### TFS scripting interface

There are a few main functions that are needed when creating scripts.

The current scripting interfaces are: Actions, Chatchannels, Creaturescripts, Events, Globalevents, Monsters, Movements, Npc, Spells, Talkactions and Weapons.

For scripting purposes, you should use some reference or memorize the main functions used in these interfaces:

**Actions:**

```lua
function onUse(player, item, fromPosition, target, toPosition, isHotkey)
```

**Chatchannels:**

```lua
function canJoin(player)
function onSpeak(player, type, message)
```

**Creaturescripts:**

```lua
function onLogin(player)
function onLogout(player)
function onThink(creature, interval)
function onPrepareDeath(creature, killer)
function onDeath(creature, corpse, killer, mostDamageKiller, lastHitUnjustified)
function onKill(creature, target)
function onAdvance(player, skill, oldLevel, newLevel)
function onModalWindow(player, modalWindowId, buttonId, choiceId)
function onTextEdit(player, item, text)
function onHealthChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin)
function onManaChange(creature, attacker, manaChange, origin)
function onExtendedOpcode(player, opcode, buffer)
```

**Globalevents:**

```lua
function onThink(interval)
function onStartup()
function onShutdown()
function onRecord(current, old)
function onTime()
```

**Monsters:**

```lua
function onThink(interval)
function onCreatureMove(creature, newTile, newPos, oldTile, oldPos, teleport)
function onCreatureDisappear(creature, isLogout)
function onCreatureAppear(creature, isLogin)
function onCreatureSay(creature, type, text)
```

**Movements:**

```lua
function onStepIn(creature, item, toPosition, fromPosition)
function onStepOut(creature, item, toPosition, fromPosition)
function onEquip(player, item, slot)
function onDeEquip(player, item, slot)
function onAddItem(moveitem, tileitem, pos)
function onRemoveItem(moveitem, tileitem, pos)
```

**Npc:**

```lua
function onCreatureAppear(cid)
function onCreatureDisappear(cid)
function onCreatureSay(cid, type, msg)
function onThink()
```

**Spells:**

```lua
function onCastSpell(creature, variant)
```

**Talkactions:**

```lua
function onSay(player, words, param)
```

**Weapons:**

```lua
function onUseWeapon(player, variant)
```


# Opening your server to the public

Whether you're looking to just open your server to let your friends play, or you want to have a serious project and you want players to come on your server, you will need to know how to make it public.

Your two choices of making your server public are either buying a host and setting your server up on the virtual machine, or port forwarding. The best option to choose depends on what you're looking for, if you want a serious project you should buy a host, since hosts can protect your server from DDoS, and the host may be able to provide help in setting up your server. However, if you are looking to open it for a few friends, your best choice is port forwarding (unless you would like to pay for a host).

### Choosing a host

TODO

### Port forwarding

OT servers use port 7171 and 7172, which players use to connect to your server as long as they're open. Port 7171 is for logging in, and 7172 is the game port. Another port that we will be using is port 80, which allows access to websites, which we will be setting up soon.

If you do not wish to open your server to the public just yet, you may skip this section, since you do not need it to connect locally.

To port forward (aka open these ports), you need admin access to your router or modem. Log in to your router and find "Port Forward" or "Virtual Servers" (or something along the lines of those), port forwarding options are usually found under the firewall tab in your router/modem's settings.

If your router/modem gives you text boxes straight forward or gives you an "add" button, this should be the same. Set one of the boxes descriptions as whatever name you choose. After that, enter 7171/7171 for inbound/local ports. Click TCP/UDP for the type (if you do not have a TCP/UDP option, forward it twice, once with TCP and another with UDP).

Once this is done, it's time to find your IPv4 address, open command prompt and type in **ipconfig**, it should give you a list of a bunch of different things, but for now we only need the IPv4 address, which should be in the format of 192.168.x.xxxx. Once you have your IPv4 address, go back to your router/modem and enter your IPv4 address as the "Private IP Address", this should be the final box you need to fill out. Do the same process but with port 7172 and port 80.

Your ports should now be forwarded, to test if your ports are open, you can use this [port checker](https://www.canyouseeme.org/).

We're not fully done yet, we still need to edit the hosts file.

To access your hosts file, open your text editor in administrator mode first (close it and reopen it in administrator if you already have it open). Once you have your text editor open, go to **file->open file** and redirect your path at the top to **C:\Windows\System32\Drivers\etc**, open the "hosts" file by double clicking it. Now that we have the hosts file open, all you have to do at the bottom is add:

```
127.0.0.1    Your IP here
```

Of course, you will have to change "Your IP here" to what your actual IP address is (you can find your IP address by going to [ipchicken](http://www.ipchicken.com/))

After that, the file should look like this (using a sample ip)

```
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#    127.0.0.1       localhost
#    ::1             localhost

127.0.0.1    174.284.27.5
```

Once done, save the file and close it, we should be done with port forwarding now.


# TFS documentation


# TFS 1.4 official release

In this section, we will cover the official release of The Forgotten Server, TFS 1.4 !

One of the major features from this release is [Revscriptsys](https://github.com/otland/forgottenserver/wiki/Revscriptsys), which allows us to register scripts using Lua instead of XML. Another important feature is a custom RSA key loader, which will allow you to use the RSA private key from a PEM file you may generate, thereby granting more security to your server. Some of the other features are: a Docker image to easily set up TFS, storing town lists in database, POSIX signal handling...

Following these lines, you can find a changelog made of newly added features, issues that have been fixed, enhancements, and so on.

## Changelog TFS 1.4

### Features

* Revscriptsys
* Custom RSA key loader
* Docker image
* Storage of town lists in database
* Improved POSIX signal handling (SIGINT, SIGTERM, SIGHUP and SIGUSR1 signals added)
* Improved rule violation and bugs reporting system

### Functionalities changed from sources to Lua

* Commands
* Loot drop mechanism
* Actions.xml itemid increase/decrease function removed
* Party experience share
* House management
* Levitate

### Added

* Container:
  * Container:getItems(recursive)
* Creature:
  * Creature:setHealth(health)
  * Creature:setSkillLoss(skillLoss)
  * Creature:addSummon(monster)
  * Creature:removeSummon(monster)
  * Added Creature:getZone()
    * ZONE\_PROTECTION
    * ZONE\_NOPVP
    * ZONE\_PVP
    * ZONE\_NOLOGOUT
    * ZONE\_NORMAL
  * Secondary functionality for Creature:move method:
    * Creature:move(tile\[, flags = 0])
* Enums:
  * CONST\_ME\_EARLY\_THUNDER
  * CONST\_ME\_RAGIAZ\_BONECAPSULE
  * CONST\_ME\_CRITICAL\_DAMAGE
  * CONST\_ME\_PLUNGING\_FISH
  * MESSAGE\_GUILD
  * MESSAGE\_PARTY\_MANAGEMENT
  * MESSAGE\_PARTY
* Events:
  * Player:onReportRuleViolation(targetName, reportType, reportReason, comment, translation)
  * Player:onItemMoved(item, count, fromPosition, toPosition)
  * Party:onShareExperience(exp)
  * Monster:onDropLoot(corpse)
  * Creature:onHear(speaker, words, type)
* Game:
  * Game.getClientVersion()
* Group:
  * Group:hasFlag(flag)
* House:
  * House:getItems()
  * House:getDoorIdByPosition(position)
  * House:canEditAccessList(listId, player)
  * House:kickPlayer(player, targetPlayer)
* Item:
  * Item:getCustomAttribute(key)
  * Item:setCustomAttribute(key, value)
  * Item:removeCustomAttribute(key)
  * Item:isLoadedFromMap()
* ItemType:
  * ItemType:isBlocking()
  * ItemType:isGroundTile()
  * ItemType:isMagicField()
  * ItemType:isUseable()
  * ItemType:isPickupable()
  * ItemType:getAmmoType()
  * ItemType:getCorpseType()
* NPC system:
  * NPCs now deduct from bank account any money missing from inventory
  * Lua VoiceModule
  * Functions related to banker NPC:
    * getMoneyWeight(money)
    * getMoneyCount(string)
    * isValidMoney(money)
    * isNumber(str)
    * getPlayerDatabaseInfo(name\_or\_guid)
    * Player.depositMoney(self, amount)
    * Player.withdrawMoney(self, amount)
    * Player.canCarryMoney(self, amount)
    * Player.transferMoneyTo(self, target, amount)
* Party:
  * Party(player)
* Player:
  * Player:getSpecialSkill(specialSkillType)
  * Player:addSpecialSkill(specialSkillType, value)
    * SPECIALSKILL\_CRITICALHITCHANCE
    * SPECIALSKILL\_CRITICALHITAMOUNT
    * SPECIALSKILL\_LIFELEECHCHANCE SPECIALSKILL\_LIFELEECHAMOUNT
    * SPECIALSKILL\_MANALEECHCHANCE
    * SPECIALSKILL\_MANALEECHAMOUNT
  * Added special skill support for conditions:
    * CONDITION\_PARAM\_SPECIALSKILL\_CRITICALHITCHANCE
    * CONDITION\_PARAM\_SPECIALSKILL\_CRITICALHITAMOUNT
    * CONDITION\_PARAM\_SPECIALSKILL\_LIFELEECHCHANCE
    * CONDITION\_PARAM\_SPECIALSKILL\_LIFELEECHAMOUNT
    * CONDITION\_PARAM\_SPECIALSKILL\_MANALEECHCHANCE
    * CONDITION\_PARAM\_SPECIALSKILL\_MANALEECHAMOUNT
  * Player:hasChaseMode()
  * Player:hasSecureMode()
  * Player:getFightMode()
    * FIGHTMODE\_ATTACK
    * FIGHTMODE\_BALANCED
    * FIGHTMODE\_DEFENSE
  * Player:sendHouseWindow(house, listId)
  * Player:setEditHouse(house, listId)
  * Additional optional parameter for Player:setGhostMode method:
    * Player:setGhostMode(enabled\[, showEffect=true])
  * Secondary functionality for Player:sendTextMessage method:
    * Player:sendTextMessage(type, text, channelId)
* Tile:
  * Tile:addItem(itemId\[, count/subType = 1\[, flags = 0]])
  * Tile:addItemEx(item\[, flags = 0])
* Weapons:
  * Added death and holy elemental damage
* Other:
  * Action scripts like taming and skining
  * New monsters
  * Charges removal option in config.lua
  * Achievements system
  * isBoss flag
  * Store inbox
  * Shopping bag module
  * Server save configurations in config.lua

**Fixed**

* MonsterType:getLoot() crash
* MonsterType:isSummonable() returned wrong flag
* Combat:execute() crash
* Limited container:addItem subtype to 100
* Waiting list bug
* MoveEvent:slot(slot)
* Crash related to map cleaning
* Exception when map file does not exist is now handled
* getMinMaxValues function returned a wrong attackValue when using weapons with ammunition

### Changed

* onManaChange's parameters match onHealthChange
* Player constructor accepts GUID parameter
* Player:getDepotChest sets last depotId for saving purposes
* Player:showTextDialog(item, text) accepts item userdata
* Changed Player:addMount to accept mount name along with id
* Renamed Combat:setCondition to Combat:addCondition
* Many updates/fixes/additions in items.xml
* Cleaner and faster XTEA implementation
* Rebase of NetworkMessage methods
* Usage of STL algorithms instead of loop in vocations.cpp
* Optimizations on getSpectators
*


# LuaScript Interface

LuaScript Interface allows you to create and delete items, to find any player online, create new monsters, npc and many more.

In other words, it is your go-to friend if you want to communicate with TFS.

You can do almost anything in Lua, take the advantage and read through sections to get to know more about what you can do.


# Action

Action's Event Interface

### onUse(player, item, fromPosition, itemEx, toPosition, isHotkey)

> * **player**  -- 1st arg/parameter /***userdata***/  =  The **player** who uses the item.
> * **item** -- 2nd arg/parameter/ ***userdata***/ = The first **item** player uses/use with.
> * **fromPosition** - 3rd arg/parameter/***userdata***/ = The **position** the first item is at.
> * **itemEx** -- 4th arg/parameter/***userdata***/ = The target of item's *Use With*, can be **item** or **creature**
> * **toPosition** - 5th arg/parameter/ ***userdata***/ = The **position** the first item is used on, with crosshairs.
> * **isHotkey** - 6th arg/parameter/ ***boolean***/ = Did the player use item via hot key? **True/False**.

1. **onUse** is called whenever an item registered to the action is used.&#x20;
2. You can register actions in data/actions/**actions.xml**

   ```markup
   <action itemid="4856" script="test.lua" />
   ```

   ```markup
   <action fromid="2146" toid="2147" script="other/enchanting.lua" />
   ```
3. Alternatively you can use [revscript](#revscript-action) method to register via *lua*, by saving a .lua file in data/scripts folder.

**After you have registered your action in actions.xml you can call the event in a script like so:**

```lua
function onUse(player, item, fromPosition, target, toPosition, isHotkey)  -- can name the arguments what you like.
    local SwordLevel = player:getSkillLevel(SKILL_SWORD)
    if SwordLevel < 70 then
        player:sendCancelMessage("This technique requires a sword fighting skill of 70 or higher.")
        return false
    end

    if not item:hasAttribute(ITEM_ATTRIBUTE_EXTRADEFENSE) then
        player:sendCancelMessage("Only swords known for their well balance and extra defense are suitable for this task.")
        return false
    end

    if fromPosition:isSightClear(toPosition) then 
        player:sendCancelMessage("You must have a clear path to your target")
        return false
    end

    if target:isPlayer() then 
        player:sendCancelMessage("To execute this technique properly, the target needs to be a player.")
        return false
    end

    if isHotkey then 
        player:sendCancelMessage("You can't use this item with a hotkey!")
        return false
    end
     -- Executing the technique

    -- Teleport to the position
    player:teleportTo(toPosition)

    -- Configure bleeding damage
    local bleed = {
        damage=50,
        rounds=10,
        interval=1
    }
    -- Apply deadly bleeding attack on target
    player:addDamageCondition(target, CONDITION_BLEEDING, DAMAGELIST_CONSTANT_PERIOD, bleed.damage, bleed.interval, bleed.rounds)

    -- Warn target that they just got slashed hard from player:getName and their blood is puring out!
    target:sendTextMessage(MESSAGE_STATUS_WARNING, "You just recieved a blood gushing wound from "..player:getName().."'s deadly sword technique!")
   return true
end
```

## Revscript Action

**Revscript** share the same event **onUse()** with the same arguments listed above.

To access any events through *revscripts*, you must create a variable first to access the interface

{% hint style="warning" %}

> you **must** have **one** variable **per event** callback no matter which type of interface you wish to access!
> {% endhint %}

Here is an example.

```lua
local swordTechnique = Action() -- we created a variable to access Action interface
```

**Action** has the available ***methods*** and ***event*** to use with ***revscripts***

> **Event**
>
> * [**onUse**](#action.onuse-player-item-fromposition-itemex-toposition-ishotkey)(player, item, fromPosition, itemEx, toPosition, isHotkey)
>
> **Methods**
>
> * action:**register**() -- Registers the action **event**.&#x20;
> * [action:**id**(***x***)](#action-id)    -- Registers items with **id** ***x*** for event
> * [action:**aid**(***x***)](#action-aid) -- Registers items with **action id** ***x*** for event
> * [action:**uid**(***x***)](#action-uid) -- Registers items with **unique id** ***x*** for event
> * [action:**allowFarUse**(t/f)](#action-allowfaruse) -- Allow far use? ***True/False***
> * [action:**blockWalls**(t/f)](#action-blockwalls) -- Do walls block item usage? ***True/False***
> * [action:**checkFloor**(t/f)](#action-checkfloor) -- Are we on same floor as target? ***True/False***

## Action:id()

```lua
local swordTechnique = Action() -- we created a variable to access Action interface

swordTechnique:id(2376) -- sword's itemId to register for event
```

## Action:aid()

```lua
local swordTechnique = Action() -- we created a variable to access Action interface

swordTechnique:aid(15428) -- an actionId to register for event
```

## Action:uid()

```lua
local swordTechnique = Action() -- we created a variable to access Action interface

swordTechnique:uid(1337) -- a uniqueId to register for event
```

## Action:allowFarUse()

```lua
local swordTechnique = Action() -- we created a variable to access Action interface

swordTechnique:allowFarUse(true) -- True/False. True we can be more than one square away to use
```

## Action:blockWalls()

```lua
local swordTechnique = Action() -- we created a variable to access Action interface

swordTechnique:blockWalls(true) -- True/false. True and walls will block usage of item.
```

## Action:checkFloor()

```lua
local swordTechnique = Action() -- we created a variable to access Action interface

swordTechnique:checkFloor(true) -- True/false. True and we can only use item on same floor as us.
```

**To register an Action script using the Revscript Method, please first ensure it is saved at proper directory location, inside you data/scripts folder, then you can see the same action as above demonstrated as a revscript like so:**

```lua
local swordTechnique = Action() -- we created a variable to access Action interface

-- Here we register items to use for action, using swordTechnique variable.
swordTechnique:id(2376) -- sword's itemId to register for event
swordTechnique:aid(15428) -- an actionId to register for event
swordTechnique:uid(1337) -- a uniqueId to register for event

-- Here we configure our other action methods, still using swordTechniqu variable.
swordTechnique:allowFarUse(true)
swordTechnique:checkFloors(true)
swordTechnique:blockWalls(true)

 --- Here we call the event using the same swordTechnique variable.
function swordTechnique.onUse(player, item, fromPosition, target, toPosition, isHotkey) -- can name the arguments what you like.

    local SwordLevel = player:getSkillLevel(SKILL_SWORD)
    if SwordLevel < 70 then
        player:sendCancelMessage("This technique requires a sword fighting skill of 70 or higher.")
        return false
    end


    if not item:hasAttribute(ITEM_ATTRIBUTE_EXTRADEFENSE) then
        player:sendCancelMessage("Only swords known for their well balance and extra defense are suitable for this task.")
        return false
    end


    if fromPosition:isSightClear(toPosition) then 
        player:sendCancelMessage("You must have a clear path to your target")
        return false
    end


    if target:isPlayer() then 
        player:sendCancelMessage("To execute this technique properly, the target needs to be a player.")
        return false
    end


    if isHotkey then 
        player:sendCancelMessage("You can't use this item with a hotkey!")
        return false
    end

    -- Executing the technique

    -- Teleport to the position
    player:teleportTo(toPosition)

    -- Configure bleeding damage
    local bleed = {
        damage=50,
        rounds=10,
        interval=1
    }
    -- Apply deadly bleeding attack on target
    player:addDamageCondition(target, CONDITION_BLEEDING, DAMAGELIST_CONSTANT_PERIOD, bleed.damage, bleed.interval, bleed.rounds)

    -- Warn target that they just got slashed hard from player:getName and their blood is puring out!
    target:sendTextMessage(MESSAGE_STATUS_WARNING, "You just recieved a blood gushing wound from "..player:getName().."'s deadly sword technique!")

    return true
end

-- Finally after all logic is completed, we register the event, still using swordTechnique
swordTechnique:register()
```


# ChatChannel

There are many types of events for the ChatChannel interface, here is a list.

* [**canJoin**](#canjoin-player)**(player)**
* [**onJoin**](#onjoin-player)**(player)**
* [**onLeave**](#onleave-player)**(player)**
* [**onSpeak**](#onspeak-player-type-message)**(player, type, message)**

- [x] You create a ChatChannel script in data/chatchannels/scripts folder, but
- [x] You must register ChatChannel in data/chatchannels/chatchannels.xml, here is an example

```xml
<channel id="8" name="GodChannel" script="godchat.lua" />
```

* **Alternatively you can use revscript method to register via lua, by saving a .lua file in data/scripts folder.**

**Please keep in mind you can name your script whatever you want as long as it ends in .lua, and its full name is in the xml, with script="*****scriptname.lua*****"**

## canJoin(player)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player** who is trying to join the channel

**canJoin is called whenever any player attempts to open the registered channel.**

**You can register your event in movement.xml like so:**

```xml
<channel id="8" name="GodChannel" script="godchat.lua" />
```

**You can then call the event in a script like so:**

**Example:** *godchat.lua*

```lua
function canJoin(player)
    return player:getAccountType() > ACCOUNT_TYPE_GAMEMASTER -- if account type is higher access than a gamemaster returns true to allow joining, otherwise returns false and doesn't allow access
end
```

**Always remember to return true if you wish to allow player to join the channel, false if not!**

## onJoin(player)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player** whom has just joined the channel

**onJoin is called whenever any player joins the registered chatchannel**

**You can register your event in creaturescripts.xml like so:**

```xml
<channel id="8" name="GodChannel" script="godchat.lua" />
```

**You can then call the event in a script like so:**

**Example:** *godchat.lua*

```lua
function onJoin(player)
    player:sendChannelMessage("System:", "Welcome to GodChat!", MESSAGE_STATUS_CONSOLE_RED, 8)
end
```

**onJoin will execute its logic everytime a player joins the channel, returns don't matter for this event!**

## onLeave(player)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player** who has left the registered chatchannel

**onLeave is called whenever a player leaves the registered chatchannel**

**You can register your event in creaturescripts.xml like so:**

```xml
<channel id="8" name="GodChannel" script="godchat.lua" />
```

**You can then call the event in a script like so:**

**Example:** *godchat.lua*

```lua
function onLeave(player)
    player:sendTextMessage(MESSAGE_STATUS_CONSOLE_RED, "You have left GodChat")
end
```

**onLeave will execute its logic everytime a player leaves the channel, returns don't matter for this event!**

## onSpeak(player, type, message)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player** that is removing the item
> * **type** -- 2nd arg/parameter /***integer***/ = a constant value representing the TALK\_TYPE
> * **message** -- 3rd arg/parameter /***string***/ = the text that player has sent

**onSpeak runs everytime a player in the chatchannel sends a message.**

**You can register your event in creaturescripts.xml like so:**

```xml
<channel id="8" name="GodChannel" script="godchat.lua" />
```

**You can then call the event in a script like so:**

**Example:** *godchat.lua*

```lua
function onSpeak(player, type, message)
    if player:getAccountType() == 10 then
        if message == "hidehealth" then
            player:setHiddenHealth(true)
        end
        if message == "showhealth" then
            player:setHiddenHealth(false)
        end
    else
        player:sendTextMessage(MESSAGE_INFO_DESCR, "You do not have appropriate account type to execute this channel command!")
    end
end
```

**onSpeak executes everytime a player speaks in registered channel, returns don't matter here**

**Here is a complete example including all the events in one file**

**Example in xml:**

```xml
<channel id="8" name="GodChannel" script="godchat.lua" />
```

**Example:** *godchat.lua*

```lua
function canJoin(player)
    return player:getAccountType() > ACCOUNT_TYPE_GAMEMASTER -- if account type is higher access than a gamemaster returns true to allow joining, otherwise returns false and doesn't allow access
end

function onJoin(player)
    player:sendChannelMessage("System:", "Welcome to GodChat!", MESSAGE_STATUS_CONSOLE_RED, 8)
end

function onLeave(player)
    player:sendTextMessage(MESSAGE_STATUS_CONSOLE_RED, "You have left GodChat")
end

function onSpeak(player, type, message)
    if player:getAccountType() == 10 then
        if message == "hidehealth" then
            player:setHiddenHealth(true)
        end
        if message == "showhealth" then
            player:setHiddenHealth(false)
        end
    else
        player:sendTextMessage(MESSAGE_INFO_DESCR, "You do not have appropriate account type to execute this channel command!")
    end
end
```


# CreatureEvent

There are many types of events for the CreatureEvent interface, here is a list.

* [**onLogin**](#onlogin-player)**(player)**
* [**onLogout**](#onlogout-player)**(player)**
* [**onThink**](#onthink-creature-interval)**(creature, interval)**
* [**onPrepareDeath**](#onpreparedeath-creature-killer)**(creature, killer)**
* [**onDeath**](#ondeath-creature-corpse-killer-mostdamagekiller-lasthitunjustified-mostdamageunjustified)**(creature, corpse, killer, mostDamageKiller, lastHitUnjustified, mostDamageUnjustified)**
* [**onKill**](#onkill-killer-victim)**(creature, target)**
* [**onAdvance**](#onadvance-player-skill-oldlevel-newlevel)**(player, skill, oldLevel, newLevel)**
* [**onModalWindow**](#onmodalwindow-player-modalwindowid-buttonid-choiceid)**(player, modalWindowId, buttonId, choiceId)**
* [**onTextEdit**](#ontextedit-player-item-text)**(player, item, text)**
* [**onHealthChange**](#onhealthchange-creature-attacker-primarydamage-primarytype-secondarydamage-secondarytype-origin)**(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin)**
* [**onManaChange**](#onmanachange-creature-attacker-primarydamage-primarytype-secondarydamage-secondarytype-origin)**(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin)**
* [**onExtendedOpCode**](#onextendedopcode-player-opcode-buffer)**(player, opcode, buffer)**

- [x] You can create a CreatureEvent script in data/creaturescripts/scripts folder, but
- [x] You must register CreatureEvents in data/creaturescripts/**creaturescripts.xml**, here is an example

```xml
<event type="logout" name="PlayerLogout" script="logout.lua" />
```

* **Alternatively you can use&#x20;*****revscript*****&#x20;method to register via&#x20;*****lua*****, by saving a .lua file in data/scripts folder.**
* **Any CreatureEvent that is not onLogin, must be registered to the creature using the creature:registerEvent(name) method, where name is the name of the event in the xml file (unless is revscript, then name is created when event is created), our above example would be done like this : creature:registerEvent("PlayerLogout") before it will be used by the creature.**

**Please keep in mind you can name your script whatever you want as long as it ends in .lua, and its full name is in the xml, with script=""**

## onLogin(player)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player** who is trying to login

**onLogin is called whenever any player tries to log in, its a great spot to&#x20;*****register*****&#x20;other CreatureEvents to players.**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="login" name="PlayerLogin" script="login.lua" />
```

**You can then call the event in a script like so:**

**Example:** login.lua

```lua
local firstItems = {2050, 2382} --- table with items for new player

function onLogin(player)
    if player:getLastLoginSaved() == 0 then --- player has never logged in before
        for i = 1, #firstItems do
            player:addItem(firstItems[i], 1) -- we give 1 of each item in table above to player
        end
        player:addItem(ITEM_BAG, 1) -- we give the player a bag too
    end
    return true --- we must return true to allow player to login, false or no return will keep player from logging in. 
end
```

**Always remember to return true if you wish to allow player login, returning false or not returning true will block player from logging in!**

## onLogout(player)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player** who is trying to logout

**onLogout is called whenever any player tries to logout, its a great spot to&#x20;*****unregister*****&#x20;other CreatureEvents to players.**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="logout" name="PlayerLogout" script="logout.lua" />
```

**You can then call the event in a script like so:**

**Example:** logout.lua

```lua
function onLogout(player)
    if player:isPzLocked() then
        player:sendTextMessage(MESSAGE_INFO_DESCR,"You must not be pz-locked, in order to logout")
        return false --- here we block player from logging out
    end
    --- if we made it to this point, player must not be pzlocked, so lets let him logout
    return true --- player logs out successfully
end
```

**Always remember to return true if you wish to allow player logout, returning false or not returning true will block player from logging out!**

## onThink(creature, interval)

> * **creature** -- 1st arg/parameter /***userdata***/ = The **creature** whom the event is triggering on
> * **interval** -- 2nd arg/parameter /***integer***/ = The **milliseconds** interval at which every iteration of the event will take place

**onThink is similar to an infinite loop, as it&#x20;*****does not stop unless the event is unregistered*****. It occurs every 1000 milliseconds, so once every second.**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="think" name="thinkEvent" script="think.lua" />
```

**You can then call the event in a script like so:**

**Example:** think.lua

```lua
function onThink(creature)
    if creature:isMonster() then
        creature:say("I'm hungry") --- if its a monster, says "I'm hungry"
        return -- we return now as we have done as we intended
    end

    return --- here we are returning incase creature wasn't a monster
end
```

**Returns strictly serve as a control mechanism when using this hook**

## onPrepareDeath(creature, killer)

> * **creature** -- 1st arg/parameter /***userdata***/ = The **creature** that is preparing to die
> * **killer** -- 2nd arg/parameter /***userdata***/ = The **killer** is who killed the creature

**onPrepareDeath triggers before creature death, and so you can return false to prevent the death from happening. This is particularly useful for pvp arena and special event scenarios.**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="preparedeath" name="deathPrep" script="preparedeath.lua" />
```

**You can then call the event in a script like so:**

**Example:** preparedeath.lua

```lua
function onPrepareDeath(creature, killer)
    if creature:isMonster() and killer:isMonster() then
        return false -- returning false will prevent the monster from dieing to another monster, but not give it any hp back
    end

    return true --- it wasn't a monster, killing a monster, so we allow the death by returning true
end
```

**When returning false for onPrepareDeath , the creature will not die! Return true to continue with death of creature**

## onDeath(creature, corpse, killer, mostDamageKiller, lastHitUnjustified, mostDamageUnjustified)

> * **creature** -- 1st arg/parameter /***userdata***/ = The **creature** that **has been killed**
> * **corpse** -- 2nd arg/parameter /***userdata***/ = The **corpse** is a **container** object, inherits from **item**, contains items dropped by the creature
> * **killer** -- 3rd arg/parameter /***userdata***/ = The **killer** is who killed the creature
> * **mostDamageKiller** -- 4th arg/parameter /***userdata***/ = The **mostDamageKiller** dealt most damage to the **creature**
> * **lastHitUnjustified** -- 5th arg/parameter /***boolean***/ = is **true** if killer's last hit was unjustified, ***false if not***.
> * **mostDamageUnjustified** -- 6th arg/parameter /***boolean***/ = is **true** if killer recieved ***unjustified*** from most damage to creature, **false if not** [//](broken://pages/4LBzVXkRqScfqvROcBCB): #

**onDeath triggers after creature death and is uniquely&#x20;*****suited for handling multiple killers*****, as well as determining if the death was&#x20;*****unjustified*****&#x20;or not.**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="death" name="PkRevenge" script="pkdeath.lua" />
```

**You can then call the event in a script like so:**

**Example:** pkdeath.lua

```lua
function onDeath(creature, corpse, killer, mostDamageKiller, lastHitUnjustified, mostDamageUnjustified)
    if creature:isMonster() and killer:isMonster() then
        return -- returning false would serve as same result as return here, just exits the script. So if monster killed monster, do nothing.
    end

    if not lastHitUnjustified and not mostDamageUnjustified then
        return -- exits script if this wasn't an unjust kill
    end

    if killer and mostDamageKiller then -- makes sure neither are nil
        if killer:isPlayer() and mostDamageKiller:isPlayer() then -- checks if both are player class
            if killer:getGuid() == mostDamageKiller:getGuid() then -- if both are one in the same
                return -- exits script, because we are looking for multiple players in an unjust kill
            end
            --- here we now know it has to be at least two players who took part in the kill
            corpse:remove() -- we destroyed the corpse so those pker's don't get it!
            return -- scripts purpose is served, we exit
        end
    end
end
```

**Returns strictly serve as a control mechanism when using this hook**

## onKill(killer, victim)

> * **killer** -- 1st arg/parameter /***userdata***/ = The **creature** that **has killed**
> * **victim** -- 2nd arg/parameter /***userdata***/ = The **victim** is a **creature** that died

**onKill triggers after creature death and is great for handling specific kills, ie, killed a boss, a player of a certain guild, stuff like that, without having to register to each of the victims.**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="kill" name="bossKill" script="bosskill.lua" />
```

**You can then call the event in a script like so:**

**Example:** bosskill.lua

```lua
function onKill(killer, victim)
    if not killer:isPlayer() then
        return -- killer is not a player, no need to execute any further.
    end
    if not victim:isMonster() and victim:getType():isBoss() then
        return -- victim is not a boss, no need to execute any further.
    end
    -- anything here, happens because the killer is a player, and the victim is a monsterType, that returns true with :isBoss()
    killer:sendTextMessage(MESSAGE_INFO_DESCR, "Congratulations you killed a Boss!")
end
```

**Returns strictly serve as a control mechanism when using this hook**

## onAdvance(player, skill, oldlevel, newlevel)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player** that gained a level!
> * **skill** -- 2nd arg/parameter /***integer***/ = The **skill** is an integer representing a **constant value** found here. -- insert link
> * **oldlevel** -- 3rd arg/parameter /***integer***/ = The **oldlevel** is an **integer** value of the level *before* the advancement.
> * **newlevel** -- 4th arg/parameter /***integer***/ = The **newlevel** is an **integer** value of the level *after* the advancement.

**onAdvance triggers when a player gains a level, magic level, or skill level.**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="advance" name="fishingLevels" script="fishinglevels.lua" />
```

**You can then call the event in a script like so:**

**Example:** fishinglevels.lua

```lua
function onAdvance(player, skill, oldlevel, newlevel)
    if not skill == SKILL_FISHING then -- we only run this if the skill gained was fishing skill
        return true
    end
    if newlevel >= 100 then
        player:getPosition():sendMagicEffect(CONST_ME_PLUNGING_FISH)
        player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "Congratulations you are officially a BIG FISHER!")
    end
    return true
end
```

**:TODO: Unsure atm if return true is necessary to advance or not.**

## onModalWindow(player, modalWindowId, buttonId, choiceId)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player** the modal window is being called for, the player whom its registered to.
> * **modalWindowId** -- 2nd arg/parameter /***integer***/ = The **modalWindowId** is an integer representing the modalwindow's id.
> * **buttonId** -- 3rd arg/parameter /***integer***/ = The **buttonId** is an **integer** representing
> * **choiceId** -- 4th arg/parameter /***integer***/ = The **newlevel** is an **integer** value of the level *after* the advancement.

**onModalWindow is called whenever any modalwindow is sent to the player**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="modalwindow" name="coolMenu" script="modalwindow.lua" />
```

**You can then call the event in a script like so:**

**Example:** modalwindow\.lua

```lua
function onModalWindow(player, modalWindowId, buttonId, choiceId)
    -- TODO
end
```

**:TODO:**

## onTextEdit(player, item, text)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player** the modal window is being called for, the player whom its registered to.
> * **item** -- 2nd arg/parameter /***userdata***/ = The **item** that is being edited
> * **text** -- 3rd arg/parameter /***string***/ = The **text** is the **string** that the player writes.

**onTextEdit is called whenever any writes text to any item**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="textedit" name="bookPassword" script="bookPassword.lua" />
```

**You can then call the event in a script like so:**

**Example:** bookPassword.lua

```lua
function onTextEdit(player, modalWindowId, buttonId, choiceId)
    -- TODO
end
```

**:TODO:**

## onHealthChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin)

> * **creature** -- 1st arg/parameter /***userdata***/ = The **creature** whom's health is changing, either up or down.
> * **attacker** -- 2nd arg/parameter /***userdata***/ = The **attacker** is the **creature** causing the healthchange.
> * **primaryDamage** -- 3rd arg/parameter /***integer***/ = The **primaryDamage** is the amount of health change for a primary damage type.
> * **primaryType** -- 4th arg/parameter /***integer***/ = The **primaryType** is a **constant value** found here. -- insert link
> * **secondaryDamage** -- 5th arg/parameter /***integer***/ = The **secondaryDamage** is the amount of health change for a secondary damage type.
> * **secondaryType** -- 6th arg/parameter /***integer***/ = The **secondaryType** is a **constant value** found here. -- insert link
> * **origin** -- 7th arg/parameter /***integer***/ = The **origin** is a **constant value** found here. -- insert link

**onHealthChange is called when a creatures healh changes, up or down.**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="healthchange" name="cursedhealth" script="cursedhealth.lua" />
```

**You can then call the event in a script like so:**

**Example:** cursedhealth.lua

```lua
function onHealthChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin)
    -- TODO
end
```

**:TODO:**

## onManaChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin)

> * **creature** -- 1st arg/parameter /***userdata***/ = The **creature** whom's health is changing, either up or down.
> * **attacker** -- 2nd arg/parameter /***userdata***/ = The **attacker** is the **creature** causing the healthchange.
> * **primaryDamage** -- 3rd arg/parameter /***integer***/ = The **primaryDamage** is the amount of health change for a primary damage type.
> * **primaryType** -- 4th arg/parameter /***integer***/ = The **primaryType** is a **constant value** found here. -- insert link
> * **secondaryDamage** -- 5th arg/parameter /***integer***/ = The **secondaryDamage** is the amount of health change for a secondary damage type.
> * **secondaryType** -- 6th arg/parameter /***integer***/ = The **secondaryType** is a **constant value** found here. -- insert link
> * **origin** -- 7th arg/parameter /***integer***/ = The **origin** is a **constant value** found here. -- insert link

**onManaChange is called when a players mana changes, up or down.**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="manachange" name="buffedMana" script="buffedMana.lua" />
```

**You can then call the event in a script like so:**

**Example:** buffedMana.lua

```lua
function onManaChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin)
    -- TODO
end
```

**:TODO:**

## onExtendedOpCode(player, opcode, buffer)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player**
> * **opcode** -- 2nd arg/parameter /***userdata***/ = The **opcode**
> * **buffer** -- 3rd arg/parameter /***integer***/ = The **buffer**

**onExtendedOpCode is called when**

**You can register your event in creaturescripts.xml like so:**

```xml
<event type="extendedopcode" name="opCode" script="opCode.lua" />
```

**You can then call the event in a script like so:**

**Example:** opCode.lua

```lua
function onExtendedOpCode(player, opcode, buffer)
    -- TODO
end
```

**:TODO:**


# GlobalEvents

* [**onStartup**](#onstartup)**()**
* [**onShutdown**](#onshutdown)**()**
* [**onRecord**](#onrecord)**(current, old)**
* [**onTime**](#ontime)**(interval)**
* [**onThink**](#onthink)**(interval)**

### onStartUp()

**onStartup has no parameters, requires no return, and&#x20;*****only runs once*****&#x20;during the start of the server.**

**Example** *startup.lua*

```lua
function onStartup()
    print("There are " ..#Game.getHouses().. " houses registered to this map")
end
```

**You can register in data/globalevents/globalevents.xml by using type="*****startup*****" like so:**

```xml
<globalevent type="startup" name="ServerStartup" script="startup.lua" />
```

### onShutdown()

**onShutdown has no parameters, requires no return, and&#x20;*****only runs once*****&#x20;during the shutdown of the server**

**Example** *shutdown.lua*

```lua
function onShutdown()
    for index, player in pairs(Game.getPlayers()) do
        player:save()
    end
end
```

**You can register in data/globalevents/globalevents.xml by using type="*****shutdown*****" like so:**

```xml
<globalevent type="shutdown" name="ServerShutdown" script="shutdown.lua" />
```

### onRecord(current, old)

**onRecord has two parameters,&#x20;*****requires return true*****, and runs each time a new record is made for most players online**

> * **current** -- number value of new record, for most players online
> * **old** -- number value of old record, for most players online

**Example** *record.lua*

```lua
function onRecord(current, old)
    addEvent(Game.broadcastMessage, 150, "New record: " .. current .. " players are logged in.", MESSAGE_STATUS_DEFAULT)
    return true
end
```

**You can register in data/globalevents/globalevents.xml by using type="*****record*****" like so:**

```xml
<globalevent type="record" name="PlayerRecord" script="record.lua" />
```

### onTime()

**onTime has one parameter which represents the&#x20;*****time*****&#x20;it executes, requires return true, and runs each each day at same time**

**Example** *ontime.lua*

```lua
function onTime(interval)
    Game.startRaid("Dragons")
    return true
end
```

**You can register in data/globalevents/globalevents.xml by giving it a unique name and setting the time using time="*****time*****" like so:**

```xml
<globalevent name="StartDragonRaid" time="09:55:00" script="ontime.lua" />
```

### onThink()

**onThink has one parameter which represents how often it executes in&#x20;*****milliseconds*****, requires return true, and runs as often as specified in&#x20;*****globalevents.xml***

**Example** *onthink.lua*

```lua
function onThink(interval)
    for index, player in pairs(Game.getPlayers()) do
        player:save()
    end
    return true
end
```

**You can register in data/globalevents/globalevents.xml by giving it a unique name and setting how often it will execute using interval="1000"&#x20;*****time is in milliseconds***

```xml
<globalevent name="SaveOnThink" interval="10000" script="onthink.lua" />
```

{% hint style="warning" %}
The above will execute every **ten** seconds **10** \* 1000 = ***10000***
{% endhint %}


# MoveEvent

There are many types of events for the MoveEvent interface, here is a list.

* \[onStepIn(creature, item, pos, fromPosition)]
* \[onStepOut(creature, item, pos, fromPosition)]
* \[onEquip(player, item, slot, isCheck)]
* \[onDeEquip(player, item, slot, isCheck)]
* \[onAddItem(moveitem, tileitem, pos)]
* \[onRemoveItem(moveitem, tileitem, pos)]

1. You can create a MoveEvent script in data/movements/scripts folder, but
2. You must register MoveEvents in data/movements/movements.xml, here is an example

```xml
<movevent event="StepIn" itemid="293" script="decay.lua" />
```

1. Alternatively you can use revscript method to register via lua, by saving a .lua file in data/scripts folder.

**Please keep in mind you can name your script whatever you want as long as it ends in .lua, and its full name is in the xml, with script=""**

## onStepIn(creature, item, pos, fromPosition)

> * **creature** -- 1st arg/parameter /***userdata***/ = The **creature** who is doing the stepin movement
> * **item** -- 2nd arg/parameter /***userdata***/ = The **item** that is being stepped on.
> * **pos** -- 3rd arg/parameter /***userdata***/ = The **position** for the location being stepped on
> * **fromPosition** -- 4th arg/parameter /***userdata***/ = The **position** which the creature moved from

onStepin is called whenever any creature steps on the registered item id(s)

**You can register your event in movement.xml like so:**

```xml
<movevent event="StepIn" fromid="11165" toid="11188" script="mud.lua" />
```

**You can then call the event in a script like so:**

mud.lua

```lua
local combat = Combat()
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_RED)

local condition = Condition(CONDITION_PARALYZE)
condition:setParameter(CONDITION_PARAM_TICKS, 20000)
condition:setFormula(-1, 80, -1, 80)
combat:addCondition(condition)

function onStepIn(creature, item, pos, fromPosition)
    if not creature:hasCondition(CONDITION_PARALYZE) then
        combat:execute(creature, Variant(creature))
    end
    return true
end
```

**Always remember to return true if you wish to allow creature to step there, returning false or not returning true will block creature from stepping there!**

## onStepOut(creature, item, pos, fromPosition)

> * **creature** -- 1st arg/parameter /***userdata***/ = The **creature** who is doing the stepin movement
> * **item** -- 2nd arg/parameter /***userdata***/ = The **item** that is being stepped on.
> * **pos** -- 3rd arg/parameter /***userdata***/ = The **position** for the location being stepped on
> * **fromPosition** -- 4th arg/parameter /***userdata***/ = The **position** which the creature moved from

onStepOut is called whenever any player tries to step off registered item id(s)

**You can register your event in creaturescripts.xml like so:**

```xml
<movevent event="StepOut" fromid="11165" toid="11188" script="mud.lua" />
```

**You can then call the event in a script like so:**

mud.lua

```lua
local mudIds = {11165, 11166, 11167, 11168, 11169, 11170, 11171, 11172, 11173, 11174, 11175, 11176, 11178, 11179, 11180, 11181, 11182, 11183, 11184, 11185, 11186, 11187, 11188}

function onStepOut(creature, item, pos, fromPosition)
    for i = 1, #mudIds do
        if Tile(fromPosition):getItemById(mudIds[i]) then
            pos:sendDistanceEffect(fromPosition, CONST_ANI_SMALLEARTH, creature)
        end
    end
    return true
end
```

**Always remember to return true if you wish to allow creature to step off the tile they are on, returning false or not returning true will block the creature from being able to step off!**

## onEquip(player, item, slot, isCheck)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player** who is equipping the item
> * **item** -- 2nd arg/parameter /***userdata***/ = The **item** that is being equipped
> * **slot** -- 3rd arg/parameter /***integer***/ = The **slot** item is being equipped to, represents a const value.
> * **isCheck** -- 4th arg/parameter /***boolean***/ = is this before item is equipped, true or false

onEquip runs twice everytime a player equips an item. It runs once before it is equipped, and runs again after. The parameter "isCheck" is true value the first time, before the item is equipped, and false the second time, after it is equipped. This is kind of unique to consider as it is one item with one registered event that runs two times.

**You can register your event in creaturescripts.xml like so:**

```xml
   <movevent event="Equip" itemid="8891" slot="armor" script="pallyarmor.lua">
       <vocation name="Paladin" />
       <vocation name="Royal Paladin" showInDescription="0" />
```

**You can then call the event in a script like so:**

pallyarmor.lua

```lua
function onEquip(player, item, slot, isCheck)
    if isCheck then
        return true -- we return true here because we don't want to apply anything until after armor is equipped.
    end

    player:setCapacity(player:getCapacity() + 20)

    return true
end
```

**Must return true to equip without error!**

## onDeEquip(player, item, slot, isCheck)

> * **player** -- 1st arg/parameter /***userdata***/ = The **player** that is removing the item
> * **item** -- 2nd arg/parameter /***userdata***/ = The **item** that is being removed
> * **slot** -- 3rd arg/parameter /***userdata***/ = The **slot** that the item is being removed from.
> * **isCheck** -- 4th arg/parameter /***userdata***/ = is this before item is removed, true or false

onDeEquip runs twice everytime a player de-equips an item. It runs once before it is de-equipped, and runs again after. The parameter "isCheck" is true value the first time, before the item is de-equipped, and false the second time, after it is de-equipped. This is kind of unique to consider as it is one item with one registered event that runs two times.

**You can register your event in creaturescripts.xml like so:**

```xml
<movevent event="DeEquip" itemid="8891" slot="armor" script="pallyarmor.lua" />
```

**You can then call the event in a script like so:**

pallyarmor.lua

```lua
function onDeEquip(player, item, slot, isCheck)
    if isCheck then
        return true -- we return true here because we don't want to apply anything until after armor is removed
    end

    player:setCapacity(player:getCapacity() - 20)

    return true
end
```

**Must return true to remove item without error!**


# Lua functions

## Game

### Available methods:

* [broadcastMessage(message, messageType)](/tfs-documentation/lua_functions#Game-broadcastMessage)
* [convertIpToString(ip)](/tfs-documentation/lua_functions#Game-convertIpToString)
* [createItem(itemId, count\[, position\])](/tfs-documentation/lua_functions#Game-createItem)
* [createContainer(itemId, size\[, position\])](/tfs-documentation/lua_functions#Game-createContainer)
* [createMonster(monsterName, position\[, extended = false\[, force = false\]\])](/tfs-documentation/lua_functions#Game-createMonster)
* [createNpc(npcName, position\[, extended = false\[, force = false\]\])](/tfs-documentation/lua_functions#Game-createNpc)
* [createTile(x, y, z\[, isDynamic = false\])](/tfs-documentation/lua_functions#Game-createTile)
* [createTile(position\[, isDynamic = false\])](/tfs-documentation/lua_functions#Game-createTile)
* [getExperienceStage(level)](/tfs-documentation/lua_functions#Game-getExperienceStage)
* [getGameState()](/tfs-documentation/lua_functions#Game-getGameState)
* [getHouses()](/tfs-documentation/lua_functions#Game-getHouses)
* [getMonsterCount()](/tfs-documentation/lua_functions#Game-getMonsterCount)
* [getNpcCount()](/tfs-documentation/lua_functions#Game-getNpcCount)
* [getPlayerCount()](/tfs-documentation/lua_functions#Game-getPlayerCount)
* [getPlayers()](/tfs-documentation/lua_functions#Game-getPlayers)
* [getReturnMessage(value)](/tfs-documentation/lua_functions#Game-getReturnMessage)
* [getReverseDirection(direction)](/tfs-documentation/lua_functions#Game-getReverseDirection)
* [getSkillType(weaponType)](/tfs-documentation/lua_functions#Game-getSkillType)
* [getSpectators(position\[, multifloor = false\[, onlyPlayer = false\[, minRangeX = 0\[, maxRangeX = 0\[, minRangeY = 0\[, maxRangeY = 0\]\]\]\]\]\])](/tfs-documentation/lua_functions#Game-getSpectators)
* [getStorageValue(key)](/tfs-documentation/lua_functions#Game-getStorageValue)
* [getTowns()](/tfs-documentation/lua_functions#Game-getTowns)
* [getWorldType()](/tfs-documentation/lua_functions#Game-getWorldType)
* [loadMap(path)](/tfs-documentation/lua_functions#Game-loadMap)
* [setGameState(state)](/tfs-documentation/lua_functions#Game-setGameState)
* [setStorageValue(key, value)](/tfs-documentation/lua_functions#Game-setStorageValue)
* [setWorldType(type)](/tfs-documentation/lua_functions#Game-setWorldType)
* [startRaid(raidName)](/tfs-documentation/lua_functions#Game-startRaid)

#### Game.broadcastMessage(message, messageType)

> **Description:** Send message to all players **Parameters:** **Returns:** Nothing **Example:**
>
> ```lua
> local message = 'Hello'
> local messageType = MESSAGE_STATUS_DEFAULT
> Game.broadcastMessage(message, messageType)
> ```
>
> **Added in version:** 1.0

#### Game.convertIpToString(ip)

> **Description:** Convert numeric representation of IPv4 to string with dot separated octets **Parameters:** **Returns:** String **Example:**
>
> ```lua
> function Player:onLook(thing, position, distance)
>   if thing:isCreature() then
>     if thing:isPlayer() then
>       local playerIp = thing:getIp()
>       local ip = Game.convertIpToString(playerIp)
>       local description = string.format("IP: [%s].", ip)
>     end
>   end
>   self:sendTextMessage(MESSAGE_INFO_DESCR, description)
>   return true
> end
> ```
>
> **Added in version:** 1.0

#### Game.createItem(itemId, count\[, position])

> **Description:** Creates an item.\
> **Parameters:** **Returns:** The item created. (userdata)\
> **Example:**
>
> ```lua
> -- Create an item somewhere on the map.
> local item = Game.createItem(2400, 1, Position(100, 100, 7))
> --
> -- Create a temporary item that is given to a player (if it isn't moved from creation it will be deleted)
> local player = Player(...)
> player:addItemEx(Game.createItem(2400, 1))
> ```
>
> **Added in version:** 1.0

#### Game.createContainer(itemId, size\[, position])

> **Description:** Creates a container with given size.\
> **Parameters:** **Returns:** The container created. (userdata)\
> **Example:**
>
> ```lua
> -- Create an amulet of loss as a container with size 5 at position: x 100, y 100, z 7.
> local item = Game.createContainer(ITEM_AMULETOFLOSS, 5, Position(100, 100, 7))
> --
> -- Create a temporary container that is given to a player (if it isn't moved from creation it will be deleted)
> local player = Player(...)
> player:addItemEx(Game.createContainer(ITEM_AMULETOFLOSS, 5))
> ```
>
> **Added in version:** 1.1

#### Game.createMonster(monsterName, position\[, extended = false\[, force = false]])

> **Description:** Creates a monster.\
> **Parameters:** **Returns:** The monster created. (userdata)\
> **Example:**
>
> ```lua
> -- This should always create this monster.
> local monster = Game.createMonster("demon", Position(100, 100, 7), false, true)
> if not monster then
>     -- Something went wrong?
> end
> ```
>
> **Added in version:** 1.0

#### Game.createNpc(npcName, position\[, extended = false\[, force = false]])

> **Description:** Creates a npc.\
> **Parameters:** **Returns:** The npc created. (userdata)\
> **Example:**
>
> ```lua
> -- This may possibly not create the npc.
> local npc = Game.createMonster("some npc", Position(100, 100, 7), false, false)
> if not npc then
>     -- Something is probably blocking that position and around it aswell
> end
> ```
>
> **Added in version:** 1.0

#### Game.createTile(x, y, z\[, isDynamic = false])

> **Description:** Creates a tile if it can.\
> **Parameters:** **Returns:** The tile created or the previous existing one. (userdata)\
> **Example:**
>
> ```lua
> local tile = Game.createTile(100, 100, 7)
> local ground = tile:getGround()
> if ground then
>     print(ground:getName())
> end
> ```
>
> **Added in version:** 1.0

#### Game.createTile(position\[, isDynamic = false])

> **Description:** Creates a tile if it can.\
> **Parameters:** **Returns:** The tile created or the previous existing one. (userdata)\
> **Example:**
>
> ```lua
> local tile = Game.createTile(Position(100, 100, 7))
> local ground = tile:getGround()
> if ground then
>     print(ground:getName())
> end
> ```
>
> **Added in version:** 1.0

#### Game.getExperienceStage(level)

> **Description:** Find the experience rate related to a certain level.\
> **Parameters:** **Returns:** The experience rate related to the specified level.\
> **Example:**
>
> ```lua
> -- Print the experience rate for level 8 to the console
> print(Game.getExperienceStage(8))
> ```
>
> **Added in version:** 1.0

#### Game.getGameState()

> **Description:** Gets the current gamestate.\
> **Parameters:** None\
> **Returns:** Current gamestate on the server.\
> **Example:**
>
> ```lua
> print(Game.getGameState())
> ```
>
> **Added in version:** 1.0

#### Game.getHouses()

> **Description:** Get all houses.\
> **Parameters:** None\
> **Returns:** A table containing all houses (userdata).\
> **Example:**
>
> ```lua
> -- This prints the names of all houses that exist on the server
> local houses = Game.getHouses()
> for i = 1, #houses do
>     print(houses[i]:getName())
> end
> ```
>
> **Added in version:** 1.0

#### Game.getMonsterCount()

> **Description:** Find the total amount of monsters on the server.\
> **Parameters:** None\
> **Returns:** Total amount of monsters on the server.\
> **Example:**
>
> ```lua
> print(Game.getMonsterCount())
> ```
>
> **Added in version:** 1.0

#### Game.getNpcCount()

> **Description:** Find the total amount of npcs on the server.\
> **Parameters:** None\
> **Returns:** Total amount of npcs on the server.\
> **Example:**
>
> ```lua
> print(Game.getNpcCount())
> ```
>
> **Added in version:** 1.0

#### Game.getPlayerCount()

> **Description:** Find the total amount of players on the server.\
> **Parameters:** None\
> **Returns:** Total amount of players on the server.\
> **Example:**
>
> ```lua
> print(Game.getPlayerCount())
> ```
>
> **Added in version:** 1.0

#### Game.getPlayers()

> **Description:** Get all connected players.\
> **Parameters:** None\
> **Returns:** A table containing all connected players (userdata).\
> **Example:**
>
> ```lua
> -- This prints the names of all players connected to the server
> local players = Game.getPlayers()
> for i = 1, #players do
>     print(players[i]:getName())
> end
> ```
>
> **Added in version:** 1.0

#### Game.getReturnMessage(value)

> **Description:** Gets a message associated with the value.\
> **Parameters:** **Returns:** true\
> **Example:**
>
> ```lua
> -- This makes no sense but its an example.
> local player = Player(...)
> player:say(Game.getReturnMessage(RETURNVALUE_YOUARENOTTHEOWNER), TALKTYPE_SAY)
> ```
>
> **Added in version:** 1.0

#### Game.getReverseDirection(direction)

> **Description:** Gets reversed direction. **Parameters:** **Returns:** Direction (integer) **Example:**
>
> ```lua
> local direction = DIRECTION_NORTH
> local reversedDirection = Game.getReverseDirection(direction)
> print('Numerical value of SOUTH direction is equel '.. tostring(reversedDirection))
> ```
>
> **Added in version:** 1.0

#### Game.getSkillType(weaponType)

> **Description:** Gets skill type associatet with weapon type. **Parameters:** **Returns:** Skill type (integer) **Example:**
>
> ```lua
> local itemtype = ItemType(...)
> local weaponType = itemtype:getWeaponType()
> local skillType = Game.getSkillType(weaponType)
> ```
>
> **Added in version:** 1.0

#### Game.getSpectators(position\[, multifloor = false\[, onlyPlayer = false\[, minRangeX = 0\[, maxRangeX = 0\[, minRangeY = 0\[, maxRangeY = 0]]]]]])

> **Description:** Get all creatures in the area.\
> **Parameters:** **Returns:** A table containing creatures found (userdata).\
> **Example:**
>
> ```lua
> -- This finds all players in a 5x5 area around (100, 100, 7)
> local spectators = Game.getSpectators(Position(100, 100, 7), false, true, 0, 2, 0, 2)
> for i = 1, #spectators do
>     local spectator = spectators[i]
>     spectator:say(spectator:getName(), TALKTYPE_SAY)
> end
> ```
>
> **Added in version:** 1.0

#### Game.getStorageValue(key)

> **Description:** Get value from globalStorageTable **Parameters:** **Returns:** Value from table on empty index nil value **Example:**
>
> ```lua
> local storage = Game.getStorageValue(1)
> print(tostring(storage))
> ```
>
> **Added in version:** 1.0

#### Game.getTowns()

> **Description:** Get all towns.\
> **Parameters:** None\
> **Returns:** A table containing all towns (userdata).\
> **Example:**
>
> ```lua
> -- This prints the names of all towns that exist on the server
> local towns = Game.getTowns()
> for i = 1, #towns do
>     print(towns[i]:getName())
> end
> ```
>
> **Added in version:** 1.0

#### Game.getWorldType()

> **Description:** Gets the current world type.\
> **Parameters:** None\
> **Returns:** Current gamestate on the server.\
> **Example:**
>
> ```lua
> print(Game.getWorldType())
> ```
>
> **Added in version:** 1.0

#### Game.loadMap(path)

> **Description:** This loads a new map chunk.\
> **Parameters:** **Returns:** Nothing\
> **Example:**
>
> ```lua
> Game.loadMap("data/map/some_other_map.otbm")
> ```
>
> **Added in version:** 1.0

#### Game.setGameState(state)

> **Description:** Sets the current gamestate.\
> **Parameters:** **Returns:** true\
> **Example:**
>
> ```lua
> -- Shutdown the server
> Game.setGameState(GAME_STATE_SHUTDOWN)
> ```
>
> **Added in version:** 1.0

#### Game.setStorageValue(key, value)

> **Description:** Insert value into globalStorageTable on specific key **Parameters:** **Returns:** Nothing **Example:**
>
> ```lua
> Game.setStorageValue(1, 1000)
> ```
>
> **Added in version:** 1.0

#### Game.setWorldType(type)

> **Description:** Sets the current world type.\
> **Parameters:** **Returns:** true\
> **Example:**
>
> ```lua
> -- Change to hardcore pvp
> Game.setWorldType(WORLD_TYPE_PVP_ENFORCED)
> ```
>
> **Added in version:** 1.0

#### Game.startRaid(raidName)

> **Description:** Starts a raid if one with said name exist.\
> **Parameters:** **Returns:** true if the raid started, nil otherwise.\
> **Example:**
>
> ```lua
> if Game.startRaid("test") then
>     -- Raid was started.
> end
> ```
>
> **Added in version:** 1.0

## Global

### Available methods:

[addEvent(callback, delay, ...)](/tfs-documentation/lua_functions#addEvent) [stopEvent(eventid)](/tfs-documentation/lua_functions#stopEvent)

#### addEvent(callback, delay, ...)

> **Description:** This function is used to run other functions at a later time.\
> **Parameters:** **Returns:** The id associated with this event.\
> **Example:**
>
> ```lua
> -- Creates an event that prints "Hello World!" to the console.
> addEvent(print, 1000, "Hello World!")
> ```
>
> **Added in version:** 1.0

#### stopEvent(eventid)

> **Description:** This function is used to stop functions that should run later.\
> **Parameters:** **Returns:** true if an event was stopped, false otherwise.\
> **Example:**
>
> ```lua
> -- Creates an event that should print "Hello World!" but it's stopped before that can happen.
> local event = addEvent(print, 1000, "Hello World!")
> stopEvent(event)
> ```
>
> **Added in version:** 1.0

## os

### Available methods:

[mtime()](/tfs-documentation/lua_functions#os-mtime)

#### os.mtime()

> **Description:** Returns the Unix time (epoch) in milliseconds\
> **Parameters:** None\
> **Returns:** The Unix time (epoch) in milliseconds\
> **Example:**
>
> ```lua
> print(os.mtime() .. " milliseconds have passed since the Unix epoch")
> ```
>
> **Added in version:** 1.0

## table

### Available methods:

[create(arrayLength, keyLength)](/tfs-documentation/lua_functions#table-create)

#### table.create(arrayLength, keyLength)

> **Description:** Creates a new table with specified length.\
> **Parameters:** **Returns:** The created table.\
> **Example:**
>
> ```lua
> local t = table.create(5, 0)
> for i = 1, #t do
>     t[i] = i + 1
> end
> ```
>
> **Added in version:** 1.0


# Metatables

TFS uses lua as the scripting language. Lua contains a unique data type known as a "metatable". These metatables are lua's representation of Object Orientated Programming. Here we can find all the methods for the predefined "Objects" sent to lua.


# Game

* [Game.getSpectators()](/tfs-documentation/metatables/game_interface#game-getspectators)
* [Game.getPlayers()](/tfs-documentation/metatables/game_interface#game-getplayers)
* [Game.loadMap()](/tfs-documentation/metatables/game_interface#game-loadmap)
* [Game.getExperienceStage()](/tfs-documentation/metatables/game_interface#game-getexperiencestages)
* [Game.getMonstersCount()](/tfs-documentation/metatables/game_interface#game-getmonsterscount)
* [Game.getPlayersCount()](/tfs-documentation/metatables/game_interface#game-getplayerscount)
* [Game.getNpcCount()](/tfs-documentation/metatables/game_interface#game-getnpccount)
* [Game.getMonsterTypes()](/tfs-documentation/metatables/game_interface#game-getmonstertypes)
* [Game.getTowns()](/tfs-documentation/metatables/game_interface#game-gettowns)
* [Game.getHouses()](/tfs-documentation/metatables/game_interface#game-gethouses)
* [Game.getGameState()](/tfs-documentation/metatables/game_interface#game-getgamestate)
* [Game.setGameState()](/tfs-documentation/metatables/game_interface#game-setgamestate)
* [Game.getWorldType()](/tfs-documentation/metatables/game_interface#game-getworldtype)
* [Game.setWorldType()](/tfs-documentation/metatables/game_interface#game-setworldtype)
* [Game.getReturnMessage()](/tfs-documentation/metatables/game_interface#game-getreturnmessage)
* [Game.createItem()](/tfs-documentation/metatables/game_interface#game-createitem)
* [Game.createContainer()](/tfs-documentation/metatables/game_interface#game-createcontainer)
* [Game.createMonster()](/tfs-documentation/metatables/game_interface#game-getmonsterscount)
* [Game.createNpc()](/tfs-documentation/metatables/game_interface#game-createnpc)
* [Game.createTile()](/tfs-documentation/metatables/game_interface#game-createitem)
* [Game.createMonsterType()](/tfs-documentation/metatables/game_interface#game-createmonstertype)
* [Game.startRaid()](/tfs-documentation/metatables/game_interface#game-startraid)
* [Game.getClientVersion()](/tfs-documentation/metatables/game_interface#game-getclientversion)
* [Game.reload()](/tfs-documentation/metatables/game_interface#game-reload)

{% hint style="success" %}
Parameters in square brackets "\[parameter]" are optional

and their default value is specified after the name e.g "= false"
{% endhint %}

### Game.getSpectators()

position\[, multifloor = false\[, onlyPlayer = false\[, minRangeX = 0\[, maxRangeX = 0\[, minRangeY = 0\[, maxRangeY = 0]]]]]]

{% hint style="danger" %}
This method is pretty heavy (excessive usage might be affecting performance)
{% endhint %}

```lua
local position = Position(1000, 1000, 7)
local spectators = Game.getSpectators(position, false, true, 10, 10, 10, 10)
-- get all spectators from position in radius of 10 vertically and horizontally
for _, spectator in ipairs(spectators) do
    -- iterates over all spectators and prints their type
    print(type(spectator)) -- prints userdata
end
```

### Game.getPlayers()

```lua
local players = Game.getPlayers()
print(#players) -- prints players online
for _, player in ipairs(players) do
    -- iterate through players online and print their names
    print(player:getName()
end
```

### Game.loadMap()

path

```lua
Game.loadMap("/data/world/map.otbm")
```

### Game.getExperienceStage()

level

```lua
local experienceStage = Game.getExperienceStages(100)
print(experienceStage) -- prints current experience stage for level 100
```

### Game.getMonstersCount()

```lua
local monstersCount = Game.getMonstersCount()
print(monstersCount) -- prints number of alive monsters
```

### Game.getPlayersCount()

```lua
local playersCount = Game.getPlayersCount()
print(playersCount) -- prints number of players online
```

### Game.getNpcCount()

```lua
local npcCount = Game.getNpcCount()
print(npcCount) -- prints number of npcs
```

### Game.getMonsterTypes()

```lua
local monsterTypes = Game.getMonsterTypes()
for _, monsterType in ipairs(monsterTypes) do
    -- iterates through monster types and prints their names
    print(monsterType:getName())
end
```

### Game.getTowns()

```lua
local towns = Game.getTowns()
for _, townin ipairs(towns) do
    -- iterates through towns and prints their names
    print(town:getName()) TODO FIND THE METHOD
end
```

### Game.getHouses()

```lua
local houses = Game.getHouses()
for _, house in ipairs(houses) do
    -- iterates through houses and prints their owners guid
    print(house:getOwnerGuid())
end
```

### Game.getGameState()

```lua
local gameState = Game.getGameState()
if gameState == GAME_STATE_CLOSED then
    -- checks if server is closed, if it's then open it
    Game.setGameState(GAME_STATE_NORMAL)
end
```

### Game.setGameState()

state

```lua
Game.setGameState(GAME_STATE_NORMAL) -- sets game state to state normal
```

### Game.getWorldType()

```lua
local worldType = Game.getWorldType()
print(worldType) -- prints currently set world type ex. WORLD_TYPE_PVP
```

### Game.setWorldType()

worldType

```lua
Game.setWorldType(WORLD_TYPE_NO_PVP) -- sets current world type to non pvp
```

### Game.getReturnMessage()

returnValue

```lua
local player = Player(...)
if player then
    local returnMessage = Game.getReturnMessage(RETURNVALUE_NOTPOSSIBLE)
    print(returnMessage) -- prints Sorry not possible.
    player:sendCancelMessage(returnMessage)
end
```

### Game.createItem()

itemId\[, count\[, position]]

```lua
local item = Game.createItem(2160)
print(item) -- prints memory address
-- at this point item was created, but not added to anywhere, so it's stored in memory
-- either add it to any container
container:addItemEx(item)
-- or delete it to avoid memory leak
item:remove()

item = Game.createItem(2160, 1, Position(1001, 1000, 7)
print(item:getPosition().x) -- prints 1001
```

### Game.createContainer()

itemId, size\[, position]

```lua
local container = Game.createContainer(1987, 10)
print(container) -- prints memory address
-- at this point container was created, but not added to anywhere, so it's stored in memory
-- either add it to any container
container:addItemEx(container)
-- or delete it to avoid memory leak
container:remove()

container = Game.createContainer(2160, 10, Position(1001, 1000, 7)
print(container:getPosition().x) -- prints 1001
```

### Game.createMonster()

monsterName, position\[, extended = false\[, force = false]]

{% hint style="info" %}
**extended** means monster can be spawned in area near the specified position

**force** means monster will be always spawned in specified position, even if position is blocked
{% endhint %}

```lua
local monster = Game.createMonster("rat", Position(1000, 1000, 7), false, true)
if monster then
    print(monster:getId()) -- prints monster unique id
end
```

### Game.createNpc()

npcName, position\[, extended = false\[, force = false]]

```lua
local npc = Game.createNpc("Nekiro", Position(1000, 1000, 7), false, true)
if npc then
    print(npc:getId()) -- prints npc unique id
end
```

### Game.createTile()

x, y, z\[, isDynamic = false]

position\[, isDynamic = false]

{% hint style="info" %}
Dynamic tiles can store items and creatures, in most cases **walkable** one. (They take more memory too)
{% endhint %}

```lua
local tile = Game.createTile(1001, 1000, 7, false)
-- or Game.createTile(Position(1001, 1000, 7), false)
if tile then
    print(tile:getPosition().x) -- prints 1001
end
```

### Game.createMonsterType()

name

{% hint style="danger" %}
This method can **overwrite** already created monster types and **clear** their loot and spells
{% endhint %}

```lua
local newMonsterType = Game.createMonsterType("SpecialRat")
-- creates new (or overwrites if exists) monster type
if newMonsterType then
    print(newMonsterType:getName()) -- prints SpecialRat
end
```

### Game.startRaid()

raidName

{% hint style="warning" %}
This method might get soon deprecated in favor of raid system written in Lua
{% endhint %}

```lua
Game.startRaid("RatsThais") -- starts raid with name RatsThais
```

### Game.getClientVersion()

```lua
local clientVersion = Game.getClientVersion()
print(clientVersion) -- prints table: 0x93ff90

-- prints min and max allowed client version and version string
print(clientVersion.min, clientVersion.max, clientVersion.string)
```

### Game.reload()

reloadType

```lua
Game.reload(RELOAD_TYPE_GLOBAL) -- reloads all libs
Game.reload(RELOAD_TYPE_ACTIONS) -- reloads all actions
-- and so on...
```


# Glossary

### OTBM

Open Tibia Binary Map - a binary format in which game map is saved. It can only be viewed and edited using a special map editor, such as RME.

### RME

Remere's Map Editor - a map editor that can handle OTBM maps. Official site: [https://remeresmapeditor.com](https://remeresmapeditor.com/)

### TFS

The Forgotten Server - engine for running your own OTS. It was originally a fork of OTServ. Now the most stable, powerful and up to date engine still in development. See: <https://github.com/otland/forgottenserver>.


# Running your first ubuntu linux OT

## Getting started

Rent a Ubuntu Server 18.04 or higher from a trusted hosting company such or install for the sake of learning experience Ubuntu Server 18.04 or higher in VirtualBox.

Once you're set we will start by accessing our server. If you're on windows you should get putty(<https://www.putty.org/>), if you're on macOS or Linux you can use the terminal which is standard available. With putty just follow the screen ( insert your domain/ip-address and click ok ) for macOS and linux users type:

```bash
ssh username@domain/ipaddress
```

`username example => root domain/ipaddress example => yourdomain.com or 127.0.0.1`

Now you will be prompted for your password (if in putty you will be prompted for the password as soon you click on Open) Insert your password and presh enter (you will not see what you type, so make sure you type your password in the right order). Now we are in our server :)

### Update and Upgrade the system

The first thing we will do is updating our Ubuntu Server with the following command

```bash
sudo apt update && sudo apt upgrade -y
```

We are using 'sudo' since I do not know if you're running as root user or as regular user. When you're logged in as regular user. No problem! Just enter your password when the terminal asks for your password. With the command above you will update the connected repository's the server is connected to and when the server is done updating the repository's it will directly upgrade all the packages which were updated.

## Installing the webserver

Now we will get to the more difficult part of the entire server setup, installing nginx, php-fpm, mariadb-server with phpmyadmin.

```bash
sudo apt install nginx php-fpm mariadb-server -y
```

The installation process is now triggered.When this is finished we will install phpmyadmin to handle our database server (which is mariadb)

```bash
sudo apt install phpmyadmin -y
```

Now we are set to get some configurations going!

### Configuring the webserver

First we want to know which version of php-fpm is installed we will check this by writing the following command in the terminal

```bash
sudo php -v
```

The output will be looking something similar as this (I am using ubuntu 19.10 here which uses php version 7.3 as default. If you're running on a server you most likely run on 18.04 lts or with the newest version 20.04 lts):

![phpversion](https://worldofcoding.net/github-img/otland-gitbook/phpversion.png)

Second we want to do is enabling php in our nginx server and setting the configuration just as we want. So we will be going to edit our nginx config. Now we need to install a command line text editor called "vim". After that we installed it we will directly open the configuration file.

```bash
sudo apt install vim -y && sudo vim /etc/nginx/sites-available/default
```

Now sit straight up and read carefully on what we're going to do. I am going to give you a few options in the configuration. Underneath here you will find the default configuration file of nginx. ( I only took the part of the config file we are in need to use and left out all the comments which we do use in this tutorial )

### Changing the web-root

We can change the 'root' directory of the website folder, if you're only using your server as root leave it in '/var/www/html'. When using it as for example 'john' you can change the directory to your default directory when you come when you login which is: '/home/john' in the default directory of john you can do 'mkdir www' to create a directory for the website and set: '/home/john/www' on line '5' instead of '/var/www/html'.

### Configuring php

I already enabled php here by writing 'index.php' on line number '24'. I've uncommented the php location settings we need to use. To make it easy and understanding I made own comments for you guys to know which lines to comment and uncomment, depending on which Ubuntu Server version you are running ( and assuming you're using Ubuntu Server 18.04 lts ).

```bash
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.php index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        location ~ \.php$ {
               include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
        ################## UBUNTU 18.04 LTS ##################
               fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        ################## UBUNTU 20.04 LTS ##################
        #       fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;

        }

}
```

Now we have to save the file and quit the file, we do this the following way: `CTRL+C` After that you will just write `:wq` press enter and we have saved and quit the file :)

We are set with the entire webserver now and so its time to check if we actually did everything as we supposed to do, but first we have to restart our web features. We do this with the following commands: `Change the number of the php-fpm version to one you're using!!!`

```bash
sudo systemctl restart nginx
sudo systemctl restart php7.2-fpm
```

Lets open our browser and goto your ip-address and see how wonderful you are! Your very own setup and configured server!

## Setup the database user + phpmyadmin

We need to create ourselves a mysql admin account. We will be doing this the following way. Please follow the steps carefully :)

```bash
sudo mariadb
```

![](https://995696672-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVBMVPm-MlN4K7ZoPJo%2F-M6Qf82HLU3vkuGg3TwF%2F-M6QfV513O28SHpH2HUQ%2Fmariadb.png?alt=media\&token=d06d2f4c-3920-4637-a9b3-a0c7549ca0ea)

#### You are inside the database right now!

We will be creating the user 'otadmin' with the password of 'otadminpassword', change these values to what you want it to be!

```bash
create user 'otadmin'@'localhost' identified by 'otadminpassword';
grant all privileges on *.* to 'otadmin'@'localhost';
flush privileges;
exit;
```

Insert these lines one by one. Now we have setup our database superuser :)

### Configure phpmyadmin

Setup phpmyadmin to access your database via the browser.

Insert the following configuration in a new file inside the nginx folder. The following command will create the file and when you are in insert the configuration posted below. ( same as for the webserver nginx configuration I have made comments for the ubuntu versions inside the php location ) `sudo vim /etc/nginx/sites-available/phpmyadmin`

```bash
server {
    listen      2344;
    server_name  _;
    root /usr/share/phpmyadmin;

    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";

    client_max_body_size 256M;
    error_page 404 @notfound;

    location / {
        index index.html index.php;
        try_files $uri $uri/ /index.php?$args;
    }

    location ~* \.(gif|jpg|jpeg|png|bmp|js|css)$ {
        expires max;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;

    ################## UBUNTU 18.04 LTS ##################
           fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    ################## UBUNTU 20.04 LTS ##################
    #       fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;

    }

    location @notfound {
        return 404 "You're not browsing correctly.";
        add_header Content-Type text/plain always;
    }

}
```

Now we have to save the file and quit the file, we do this the following way: `CTRL+C` After that you will just write `:wq` press enter and we have saved and quit the file :)

Now we have to enable the phpmyadmin configuration for nginx we do that by running the next command: `sudo ln -s /etc/nginx/sites-available/phpmyadmin /etc/nginx/sites-enabled/phpmyadmin`

Finally restart the nginx server with `sudo systemctl restart nginx` and we will be able to access phpmyadmin by <http://youripordomain:2344> login with the database username and password we've created.

## Setup your Server for TFS

First of all we need to install a few packages to our system which makes us able to build the TFS sources.

Directly copy'd from the TFS github wiki(<https://github.com/otland/forgottenserver/wiki/Compiling-on-Ubuntu>):

### Install the required software

The following command will install Git, CMake, a compiler and the libraries used by The Forgotten Server.

Git will be used to download the source code, and CMake will be used to generate the build files.

```bash
sudo apt-get install git cmake build-essential liblua5.2-dev libgmp3-dev libmysqlclient-dev libboost-system-dev libboost-iostreams-dev libboost-filesystem-dev libpugixml-dev libcrypto++-dev libfmt-dev
```

### Download the source code

```bash
git clone --recursive https://github.com/otland/forgottenserver.git
```

### Generate the build files

```bash
cd forgottenserver
mkdir build && cd build
cmake ..
```

### Build

```bash
make
```


# Introduction

The goal of this guide is to provide a way for anybody to learn Lua, regardless of previous programming experience or knowledge of programming fundamentals.

###


# Introduction

What you'll need to know before moving on.

* [Types](/lua-guide/fundamentals-1/types)
* [Variables](/lua-guide/fundamentals-1/variables)
* [Operators](/lua-guide/fundamentals-1/operators)
* [Control Structures](/lua-guide/fundamentals-1/control-structures)
* Conditions
* [Loops](/lua-guide/fundamentals-1/loops)
* Functions
* [Scopes](/lua-guide/fundamentals-1/scopes)
* File Handling (I/O)
* Object-Oriented-Programming


# Types

### Quick Description

* nil: A type to denote a value that is nothing, nonexistent, null.
* string: A sequence of characters (letters, symbols, numbers).
* number: Any kind of number.
* boolean: Two types of values, true or false.
* function: A chunk of redistributable code to be executed at a later time.
* table: The only data structure in the language, holds *key, value* pairs.
* userdata: A chunk of memory which holds C data (Lua's parent language).
* thread: A reference to a coroutine.

## More Information & Examples

Since userdata and threads are advanced and are rarely used, they will not be covered here.

### nil

```lua
local x = nil -- define x, but holds no value as denoted by nil
```

```lua
local x = 5 -- start out with a number value
x = nil -- reassign x to hold no value
```

### string

```lua
local message = "Hello, world!" -- double quote definition
print(message) -- will output to console: Hello, world! without quotes
```

```lua
local message = 'Hello, world!' -- single quote definition
print(message) -- will output to console: Hello, world! without quotes
```

#### Escape Sequences

Escape sequences are a way to translate its sequence into a different character that may be difficult or impossible to respresent in a string. In Lua, the escape sequence is denoted by a backslash followed by a special character.

* **\\"**: double quote
* **\\'**: single quote
* **\\\\**: backslash
* : new line

{% hint style="info" %}
These are the main escape sequences you'll ever need to use, if you wish to see the full list, check out the Auxiliary chapter of this book.
{% endhint %}

This is a string utilizing the double quote escape sequence to insert a literal double quote into the string. The reason for this is that if you do this without using an escape sequence, you will break out of the string because a string starts with the first quote and ends with the second. More about this can be read in the [Operators](/lua-guide/fundamentals-1/operators) page.

```lua
print("I love the language called \"Lua\"!") -- Output: I love the language called "Lua"!
```

The same can be done with single quotes:

```lua
print('I love the language called \'Lua\'!') -- Output: I love the language called 'Lua'!
```

Inserting literal backslashes into a string:

```lua
print("Directory: \\home\\user\\desktop") -- Output: Directory: \home\user\desktop
```

And finally, newline:

```lua
print("This string\nis split up!")
--[[ Output:
This string
is split up!
]]
```

Here is a string that cannot have any escape sequences in it, everything is interpreted as raw characters.

```lua
local message = [[Escape\n sequences\\ do \"nothing\' here!]]
print(message) -- Output: Escape\n sequences\\ do \"nothing\' here!
```

### number

The main thing that might not be obvious is the use of `e` , which means the following number is an exponent.

```lua
print(5) -- Output: 5
print(5.0) -- Output: 5.0
print(5.25225) -- Output: 5.25225
print(0.5e1) -- Output: 5.0
```

### boolean

Booleans are simple, there are only 2 possible values: `true` and `false`. Their main use is to indicate whether or not an operation or function call is successful, and used to indicate truthiness in a condition expression, which is covered in the [Operators](/lua-guide/fundamentals-1/operators) page.

### table

Tables are (in my opinion) the most fun & complex data type Lua has to offer. They hold key, value pairs of data which can let you hold any kind of data you want in any order or way you'd like. The easiest way to learn how it works, is by thinking of tables as a ton of storage lockers. With a storage locker, you need a key to access what's inside of it, the same concept applies to tables. The keys for tables can be any type of value (except `nil`), and the value can be any type of value. All values must be separated by a comma.

Keys are denoted by either `[key]` or `key`. If square brackets are used, the key can be of any type, but writing the key plainly is a shortcut for a key with a `string` type. Here's a simple example of an array of numbers:

```lua
local array = {1, 2, 3}
```

You can see here that no keys are explicitly defined. If you don't explicitly define keys, they are automatically ordered starting from 1. Here's the exact same array but written with keys to show what it looks like:

```lua
local array = {
    [1] = 1,
    [2] = 2,
    [3] = 3
}
```

Both are equivalent, however, the first one is much shorter and easier to look at if you understand how it works internally.

Here is an example of what a player might look like for a game:

```lua
local player = {
    name = "John",
    health = 100,
    level = 5
}
```

Each key in this example is a `string` type, since no brackets are used. The exact same can be written with square brackets like so:

```lua
local player = {
    ["name"] = "John",
    ["health"] = 100,
    ["level"] = 5
}
```

Tables can also be nested (a table inside of a table), here's an example:

```lua
local player = {
    name = "John",
    health = 100,
    level = 5,
    friends = {"Jake", "Freddie"}
}
```

Again, since there's no explicit definition of the keys, they are automatically ordered starting from 1. To access tables, you can use either the `table[key]` syntax, or `table.key`. The difference between both is the same concept as before: with square brackets the key can be of any type, with the period the key must be a `string`. Here's an example:

```lua
local player = {
    name = "John",
    health = 100,
    level = 5,
    friends = {"Jake", "Freddie"}
}

print(player.name) -- Output: John
print(player["name"]) -- Output: John
```

### function

Functions are extremely powerful, they allow you to reuse code at any time of your choosing instead of having to copy/paste a set of code over and over again, which results in cleaner and more organized code.

Take this function for example, this defines a new function called `average` which calculates the average of the parameters passed (a & b), and uses the `return` keyword to give back a value which we use to show its output to the console.

You will see the word "call" many times throughout this book, calling means to invoke or execute a function. To call a function, use parentheses + any parameters you'd like to pass after writing the name of the function, like so: `function_name(param1, param2, etc)`

```lua
function average(a, b)
    return (a + b) / 2
end

print(average(5, 7)) -- Output: 6
```

When passing an argument to a function, it is first evaluated before the value is inserted as the parameter. In the example above, `print` is called and the **result** of `average(5, 7)` is inserted as the first parameter. However, if you don't call the function, it would give an output like this:

```lua
function average(a, b)
    return (a + b) / 2
end

print(average) -- Output: function: 0x56555778d880
```

The reason it outputs the function itself, is because it isn't called. We're simply passing the function itself to the first parameter of print instead of calling it to get a result from it.

Functions can also be a part of tables, and can be explicitly defined inside of said table within the function name using the `.` syntax used for tables normally:

```lua
local a = {}

function a.something()
    print('something!')
end

a.something() -- Ouput: something!
```

This will be prudent in the future since Lua's standard libraries include functions inside of tables, such as `table.insert`, which is part of the `table` library.

Now to introduce variadic functions. These work the same as normal functions, except they have a special parameter (which is `...`) that holds any number of values passed to it. The best example of this is the `print` function, it holds any number of parameters and outputs all of them in sequence to the console. The print function is basically written as this:

```lua
function print(...)
    local arguments = {...}
    for i = 1, #arguments do
        io.write(arguments[i] .. "\n")
    end
end
```

Don't worry if you have no clue what's going on, since this uses things we haven't gone over yet (but if you'd like to understand now, head to the [Loops](/lua-guide/fundamentals-1/loops) page and come back). The gist is that `...` holds the rest of the arguments passed to the function, and it is dumped into a table so we can access them, then the rest is just outputting each argument in sequence along with a new line.

The variadic parameter doesn't have to be the only one in the parameter list, it can be used to hold any values after a specific set of arguments you'd like to take in first, like so:

```lua
function example(a, b, ...)
    -- no definition here, just an example
end

example(1, 2, 3, 4, 5, 6, "asdf", nil, "bb")
```

Parameters a & b hold 1 & 2 respectively, while the rest of the arguments are held in `...`, which can't be accessed out-of-the-box like a & b can.


# Variables

Variables are a way to name a piece of data for future reference and usage. They can be reused over and over again without having to be recalculated or manually typed out again.

An analogy that could provide understanding of variables is a box. Say you have a box and put an object inside of it, then mark it so you know what's inside for future reference. Variables are that box, the value of the variable is the object inside of it, and the mark on the box is the variable name. When you access a variable, you take that object out to use it however you'd like.

There are two types of variables, a `local` variable and a global variable. Since explaining the difference involves scopes which requires knowledge of [Control Structures](/lua-guide/fundamentals-1/control-structures), the difference will be covered later on in the [Scopes](/lua-guide/fundamentals-1/scopes) section.

For now, we'll be using the `local` keyword to define any variables. The syntax for defining a local variable is: `local variable_name = value`. Since Lua is a dynamically-typed language, there's no need to define the type of value you're using, just assign a value & go.

Example of a simple variable called x:

```lua
local x = 5
```

You can also reference the value of another variable (or itself) inside the assignment:

```lua
local x = 1
local y = x + 2 -- value of y is 3
```

Variables really help out when you have a result of an expensive operation or calculation, since you can store the value without having to do that same operation or calculation again.

```lua
local var = some_function() -- Imagine this takes 1 second to execute some_function() and returns a value of 2
print(var) -- Output: 2

-- Later on:
var = var + 2 -- This is called reassignment, since var already has a value of 2, it turns into "var = 2 + 2"
print(var) -- Output: 4
```

Since `var` is assigned to the result of the expensive function, its value can be accessed as many times as we need without having to spend another second each time we need to use that specific value.

{% hint style="info" %}
Plenty more examples for variables using different types of values are in the next page.
{% endhint %}


# Operators

Operators are a symbol(s) to perform a specific action. Operands are the values the operator uses in the action.

### Relational Operators

When using these operators, both operands must be the of the same type.

Comparing by reference means both operands must point to the exact same memory address, the value of its contents don't matter. Example:

```lua
local a = {1, 2, 3}
local b = {1, 2, 3}
local c = a -- c now also holds the same reference to the table that a does
print(a == b) -- Output: false, both have separate memory addresses
print(a == c) -- Output: true, both variables hold the same reference to the exact same table
```

{% tabs %}
{% tab title="<" %}
Operator: Less Than (`a < b`)

If the value of `a` is less than `b`, the result is `true`, otherwise, `false`.

Operands Types:

* number (compares by value)
* string (compares by alphabetical order)
  {% endtab %}

{% tab title=">" %}
Operator: Greater Than (`a > b`)

If the value of `a` is greater than `b`, the result is `true`, otherwise, `false`.

Operands Types:

* number (compares by value)
* string (compares by alphabetical order)
  {% endtab %}

{% tab title="<=" %}
Operator: Less Than or Equal To (`a <= b`)

If the value of `a` is less than or equal to `b`, the result is `true`, otherwise, `false`.

Operands Types:

* number (compares by value)
* string (compares by alphabetical order)
  {% endtab %}

{% tab title=">=" %}
Operator: Greater Than or Equal To (`a >= b`)

If the value of `a` is greater than or equal to `b`, the result is `true`, otherwise, `false`.

Operands Types:

* number (compares by value)
* string (compares by alphabetical order)
  {% endtab %}

{% tab title="==" %}
Operator: Equal (`a == b`)

If `a` is exactly equal to `b`, the result is `true`, otherwise, `false`.

Operands Types:

* number (compares by value)
* string (compares by value)
* boolean (compares by value)
* function (compares by reference)
* table (compares by reference)
* userdata (compares by reference)
* thread (compares by reference)
  {% endtab %}

{% tab title="\~=" %}
Operator: Not Equal (`a ~= b`)

If `a` is anything but `b`, the result is `true`, otherwise, `false`.

Operands Types:

* number (compares by value)
* string (compares by value)
* boolean (compares by value)
* function (compares by reference)
* table (compares by reference)
* userdata (compares by reference)
* thread (compares by reference)
  {% endtab %}
  {% endtabs %}

### Logical Operators

Note: When something is defined as being "truthy", it means that the value is considered to be `true` by Lua, which is any value that isn't `false` or `nil`.

{% tabs %}
{% tab title="and" %}
Syntax: `a and b` where a & b are both evaluated as expressions.

If `a` is truthy, `b` is the result of the operation, otherwise it is the result of `a`.

```lua
local x = true and 5 -- x is 5
local y = x and 10 -- y is 10, x is evaluated to true because 5 isn't a value of false or nil
local z = false and 100 -- false, a is not truthy thus the second value is not the result
```

{% endtab %}

{% tab title="or" %}
Syntax: `a or b` where a & b are both evaluated as expressions.

If `a` is truthy, result is `a`, otherwise `b`.

```lua
local x = true or 5 -- x is true, a is truthy so b is never evaluated
local y = false or 10 -- y is 10, a is not truthy so b is evaluated and the result
local z = (10 > 5) or (x + y) -- true, a is evaluated and 10 > 5 results in true, b is never evaluated
```

{% endtab %}

{% tab title="not" %}
Syntax: `not a`

Inverts the truthiness of `a`, any expression or value that results in true, the value is flipped to false, and vice versa.

```lua
local x = not true -- x is false
local y = not x -- y is true
```

{% endtab %}
{% endtabs %}

Here are some more examples pairing these operators together:

```lua
local x = 1
local y = 2
--    (    A operand to 'or'    )    (  B operand to 'or'  )
--    (1 > 2  and <expression>  ) or (<fallback expression>)    
print((x > y) and 'X is greater!' or 'Y is greater!') -- Output: Y is greater!
```

Since 1 (x) is not a greater number than 2 (y), the result of the `and` operator is `nil` because of the `a` operand resulting in `false`, the `or` operator comes in because the result of the `and` operation is the `a` operand to `or`, so the result looks like `nil or 'Y is greater!'`. In plain English, all that's happening here is: "If my x variable is bigger than our y variable, give me back a string that says X is greater, otherwise, give me a string that says Y is greater."

### Mathematical Operators

{% tabs %}
{% tab title="Addition (+)" %}
Syntax: `a + b`

```lua
local x = 5 + 10 -- 15
local y = 1.2 + 6.3 -- 7.5
```

{% endtab %}

{% tab title="Subtraction (-)" %}
Syntax: `a - b`

```lua
local x = 5 - 2 -- 3
local y = 2.5 - 1.2 -- 1.3
```

{% endtab %}

{% tab title="Multiplication (\*)" %}
Syntax: `a * b`

```lua
local x = 5 * 3 -- 15
local y = 1.5 * 1.5 -- 2.25
```

{% endtab %}

{% tab title="Division (/)" %}
Syntax: `a / b`

```lua
local x = 10 / 2 -- 5
local y = 9 / 2.5 -- 3.6
```

{% endtab %}

{% tab title="Exponentation (^)" %}
Syntax: `a ^ b`

```lua
local x = 5 ^ 2 -- 25
local y = 2 ^ 2.5 -- 5.65685424949
```

{% endtab %}

{% tab title="Negation (-)" %}
Syntax: `-a`

```lua
local x = -5 -- -5
local y = 10 -- 10
y = -y -- y is now -10
y = -x -- y is now 5
```

{% endtab %}
{% endtabs %}

### Concatenation

Concatenation is an operation that joins two strings together. The result is a copy of both strings joined together, since Lua cannot manipulate the contents of a string itself.

Syntax: `a .. b`

Examples:

```lua
local a = "Hello "
local b = ", world!"
print(a .. b) -- Output: Hello, world!
```

{% hint style="info" %}
You can chain these operators however many times you like in any order.
{% endhint %}

### Length

The length operator (#) is primarily used on tables, but can be effective for strings as well. For strings, it returns the number of bytes (usually each byte is a single character). For tables, it returns the length of the table as long as it has no holes and is ordered:

```lua
local t = {1, 2, 3}
print(#t) -- 3
```

Depending on the version of Lua you're using, if the array or table has nil values inbetween the other values, the result of the length operator will be different. Any keys that aren't numerical are not counted towards the length.

If you have keys that aren't numbers, or have nil values/holes in your table, a table size function can be implemented by simply using the `pairs` iterator:

```lua
function table.size(t)
    local size = 0
    for k, v in pairs(t) do
        size = size + 1
    end
    return size
end

local t = {1, 2, 3}
local t2 = {a = 5, [2] = 4, 84}
print(table.size(t), table.size(t2)) -- Output: 3 3
```


# Control Structures

Control Structures define which way a program flows. Lua provides a simple set of generic control structures seen in most languages today:

* if, then, else, elseif
* while
* repeat
* for
* break
* return

Each of these control structures determines the way your code flows in your program. Each one besides `return`, `break`, and `repeat` are terminated by the `end` keyword.

### if, then, else, elseif

An if statement tests the condition given and determines whether or not to move forward, if the condition is truthy it executes the code given in the first `if` block. Otherwise, if there is an `elseif` statement, that condition is also tested and has the exact same behavior as an `if` statement. If none of those conditions evaluate to true, the `else` block is executed. Each `if` statement should be accompanied by an `end` to terminate the control structure, you should not place them for any `else` or `elseif`s you may place. Each statement may only contain one `if`, any number of `elseif`s, one `else`, and finally one `end`.

A general if statement:

```lua
if condition then
    print('1st condition was true')
end
```

If our condition was truthy (any value that isn't `false` or `nil`), the print will be executed. Otherwise, nothing will happen.

An example using all keywords:

```lua
local x = 50
local y = 10
if (x - y) < 10 then
    print('1st condition was true')
elseif (x - y) < 20 then
    print('2nd condition was true')
else
    print('none of the conditions were true')
end
```

In this example, all conditions evaluate to false because `x - y` is 40, which is not less than 10 nor 20, resulting in the last print being executed, since the `else` keyword is a fallback in the case that no other conditions are truthy.

### while

A while loop will continuously execute its body as long as the condition provided is truthy. The condition is evaluated each time before executing the body again.

Structure of a while loop:

```lua
while condition do
    -- body
end
```

More information & examples are covered in the [Loops](/lua-guide/fundamentals-1/loops) page.

### repeat

A repeat loop will also continuously execute its body as long as the condition provided is truthy. The difference here is that the condition is evaluated after the body runs, not before. So any repeat loop will always execute at least once.

Structure of a repeat loop:

```lua
repeat
    -- body
until condition
```

More information & examples are covered in the [Loops](/lua-guide/fundamentals-1/loops) page.

### for

There are two different kinds of for loops, a numeric for, or a generic for. These also execute their bodies until the loop is terminated.

A numeric for is ran for a specific amount of times, the loop variable starts at the number provided for `start`, and stops at the number provided for `stop`. The loop variable gets incremented by the `step`each iteration, the default being 1.

```lua
for var = start,stop,step do
    -- body
end
```

A generic for loop traverses all values returned by an iterator (a function which provides a way to traverse a container, or a specific set of values)

```lua
for <loop vars> in iterator(<args>) do
    -- body
end
```

More information & examples are covered in the [Loops](/lua-guide/fundamentals-1/loops) page.

### break

A break will instantly halt execution and break any loop, and will not be able to return back to the loop.

More information & examples are covered in the [Loops](/lua-guide/fundamentals-1/loops) page.

### return

A return gives back any number of values from a function, it works like a break in the sense that it halts execution of the function and can't continue onward at any point.

```lua
function abc()
    return 1, 2, 3
end

local a, b, c = abc() -- a = 1, b = 2, c = 3
```

In this single return, 3 values are returned and can be unpacked into variables, or a table if you have no idea how many values will be returned, like this:

```lua
function abc(arg)
    if arg then
        return 1, 2, 3
    end
    return 1, 2, 3, 4, 5
end

local args = {abc(true)} -- {1, 2, 3}
args = {abc(false)} -- {1, 2, 3, 4, 5}
```

Here, the default return value is `1, 2, 3, 4, 5`, if the condition to the `if` statement is false, the default is used. However, if `arg` evaluates to true in the `if` statement, `1, 2, 3` will be returned and not `1, 2, 3, 4, 5`, since return breaks out of the function, the rest of the code will not be executed.

Since Lua automatically assigns indexes like previously discussed, unpacking it like this creates an array the same way you do it manually, which lets you use a different way to get all returned values of a function if you don't specifically know how many or what values it's returning.

If you still use variables to unpack the return values into, they are unpacked in order, so even if you have 3 variables and 5 return values, it will use the first 3 return values to assign those variables in sequence:

```lua
function abc(arg)
    if arg then
        return 1, 2, 3
    end
    return 1, 2, 3, 4, 5
end

local x, y, z = abc(false) -- returns 1, 2, 3, 4, 5 | x,y,z are 1,2,3 respectively
```


# Loops

Loops are one of the most powerful concepts in any language. They provide a way to repeat a certain process for any number of times or based off of any condition. This lets programmers simplify and condense code that could otherwise result in thousands of lines of code.

### for loops

The simplest loop is a numerical loop, described in the previous section. Here is an example of how to use one:

```lua
for i = 1, 10 do
    print(i)
end
```

Here we're able to print numbers 1 through 10 by defining the start and stop as 1, and 10 respectively. The step (increments the loop variable) is defaulted to 1, which lets us move from 1 to 10 one step at a time (hence the name `step`).

Here's what it would look like with an explicitly defined step variable:

```lua
for i = 1, 10, 2 do
    print(i)
end
```

Here's the output:

```
1
3
5
7
9
```

Since the step variable is defined as 2, each iteration it increments our loop variable `i` by 2. Since it begins with 1, it hops to 3, 5, 7, and 9. The stopping point is 10, and since after the loop variable is incremented from 9 to 11, the loop is terminated since the loop variable is greater than or equal to its stop variable.

Now, generic for loops provide a way to iterate through a set of data. Here's an example:

```lua
local t = {1, 2, 3}
for key, value in ipairs(t) do
    t[key] = value * 5
end
```

This particular chunk of code will traverse through the table and multiply each value by 5, resulting in the table looking like `{5, 10, 15}` once the loop is finished. The iterator here is `ipairs` and we pass the table to it, telling `ipairs` to traverse that specific table for us. Each iteration, `ipairs` returns a key and a value (the same key and value used in the table).

`ipairs` will only traverse an ordered set of data, like in the above example. To traverse an unordered set of data, we use `pairs`.

```lua
local t = {
    a = 5,
    b = 10,
    c = 15
}

for key, value in pairs(t) do
    t[key] = value * 3
end
```

If at least 1 key in the table is out of order, the entire data set is considered out of order, and `ipairs` will not work. By using `pairs`, Lua will traverse it in any way possible, meaning it could get to `c` before `a` and `b`, and any other possible combination.

It may help to think of `ipairs` and `pairs` as your hands when looking through a book. If you have a book with 3 pages inside, with a number on each one (1, 2, 3) respectively, if your hands worked like `ipairs`, you would look through them in order. Otherwise, if your hands worked like `pairs`, you would flip through each one randomly, and never the same one twice.

### while loops

While loops depend on a condition to be truthy in order to continue executing, this can be used for whenever you have no idea how many times to iterate, just until you need to satisfy a specific condition.

These can be volatile, since if there's an error in your logic and the condition you provide can never end up false, the loop will execute forever and take up a large chunk of CPU until you kill the program manually.

Here is a way to use a while loop to mimic a numeric for loop:

```lua
local i = 1
while i <= 15 do
    print(i)
    i = i + 1
end
```

If `i` is never incremented, the condition would never be false and the loop would run forever. This code would print all numbers from 1 to 15.

### repeat loops

These and while loops are generally the same, and this is the type of loop you'll almost never see used or have a typical use of it. But, if you understand while loops you'll understand these as well.

Repeat loops check the condition to keep running after the body is executed, instead of before execution (like a while loop does). This can let you run the body at least once and it will determine if it should continue based off of a condition you provide.

An example of a numeric for in the form of a repeat loop:

```lua
local i = 1
repeat
    print(i)
    i = i + 1
until i >= 16
```

Again, this code prints all numbers from 1 to 15. Since the condition is checked after the body is executed to determine whether or not to run another iteration, it needs to check for 16 since after the body executes the result will be incremented by the time it reaches the condition. So if we only want it to print up until 15, the condition needs to check if it's 1 higher since we increment it before we know it already hit 15.

### Using the break keyword

By using `break`, you completely terminate the loop before it reaches its natural termination. This can be useful if you're looking for a specific value in a data set, like this:

```lua
local t = {1, 2, 3}
local lookingFor = 2
for key, value in ipairs(t) do
    if value == lookingFor then
        print("found the value we're looking for!")
        break
    end
end
```

In that example, once it reaches the 2nd iteration (which will have a value of 2, since we use `ipairs` to iterate in the exact sequence the table is defined), it will print that the value is found and will completely terminate the loop, preventing it from iterating any further.


# Scopes

Scopes are what define the range of functionality to a variable or function. This specifically applies in Lua to `local` variables & functions. When you define a variable or function with `local`, its scope is defined by the innermost block of code you define it in.

Example of various scopes:

```lua
local x = 15 -- scope is script-wide, x can be accessed anywhere inside of this script

function a()
    local first = true -- first can only be accessed throughout a()'s code block
    if first then
        local second = 123 -- can only be accessed within this if statement
        print(second) -- Output: 123
    end
    print(second) -- nil, cannot access that variable anymore
    print(first) -- Ouput: true | we can access this variable since we're still inside of the function's code block
end
```

Another example showing a function's scope:

```lua
local function outputTable(t)
    local function output(t)
        for k, v in pairs(t) do
            print(k, v)
        end
    end
    output(t) -- output function is only accessible inside of outputTable
end

outputTable({1, 2, 3}) -- works, outputTable's scope is script-wide
output({1, 2, 3}) -- will return an error, output is inaccessible since it's not inside the current scope, it is inside of outputTable. 
```


# Closures

A closure is when you enclose a function inside of another, like so:

```lua
function a(var)
    local x = 5
    local function b()
       print(x, var) 
    end
    return b
 end
```

When you create a closure, all of the variables are accessible in its parent's scope. In this case, b has access to a's scope. This provides a way to access and manipulate variables inside a function after its parent returns. The variables that the closure can access are called upvalues. The variables `x` and `var` are both upvalues to function `b` in this case.

Take this example, a simple function to increment a value, which is inaccessible without the closure:

```lua
function counter()
    local i = 0
    return function()
        i = i + 1
        return i
    end
end
```

Here we define a function that returns an anonymous function (a function that has no name or identifier) which will increment the upvalue `i` and return the value back to us.

Each time we call `counter`, it generates a new counter for us, it can be called any amount of times and all the counters will have different values. Each time the returned function from counter is called (the function that increments), it will only change that counter, no others.

```lua
function counter()
    local i = 0
    return function()
        i = i + 1
        return i
    end
end

local counter_1 = counter() -- now counter_1 holds a unique function to increment the upvalue
local counter_2 = counter() -- counter_2 holds a new unique incrementer
counter_1() -- increment our first counter, i is now 1
counter_2() counter_2() counter_2() -- increment counter_2 3 times, i is 3, counter_1 is unaffected

print(counter_1(), counter_2()) -- Output: 2 4
```

For the print, the counters must be incremented again so we can get the value, since each time our incrementers run they return the variable after incrementing it.


# Iterators

Iterators provide a way to traverse data. Iterators will usually use a closure to keep track of what data it's on and uses that to determine what to give next.

Take the iterator `ipairs` for example, it traverses a table in sequence. Its implementation can be written like this:

```lua
function ipairs(t)
    local index = 0
    return function()
       index = index + 1
       if t[index] then -- check if the value exists
           return index, t[index] -- key, value
       end
       return nil 
    end
end

local t = {1, 2, 3}
for k, v in ipairs(t) do
    print(k, v)
end
```

```
Output:
1 1
2 2
3 3
```

Using closures, you can define your own way to iterate through a set of data. You could iterate half of it forward and half of it backwards, iterate the entire thing in reverse, iterate every 2 values, etc.

Here's what a reverse `ipairs` would look like:

```lua
function revipairs(t)
    local index = #t + 1 -- start at the last index in the table, +1 to make sure it hits the end value when index-1 happens
    return function()
        index = index - 1 -- travel backwards from the end
        if t[index] then -- again, checking if the value exists
            return index, t[index]
        end
        return nil
    end
end

local t = {1, 2, 3}
for k, v in revipairs(t) do
    print(k, v)
end
```

```
Output:
3 3
2 2
1 1
```


# Recursion

Recursion is a technique used to use an algorithm or function that calls itself repetitively until a certain condition is satisfied.

The go-to example for recursion is a factorial function:

```lua
function fact(n)
    if n == 0 then
        return 1
    end
    return n * fact(n - 1)
end
```

Here it will calculate the factorial by returning each value multiplied by the result of `fact(n - 1)`. It can be a bit confusing, since we know return breaks out and gives back a value to whatever called the function, but before a return can give back a value, it needs to be evaluated first. And until `n` reaches 0, it will keep trying to evaluate `n * fact(n - 1)` . Once `n` does reach 0, it returns the next multiplier (1) and then the first call to `fact` will be able to return the evaluated result. All of these is quite literally a chain of returns.

Here's a diagram of what's really happening:

```lua
fact(3)
--[[
fact(3)
|
-> return (3 * fact(2))
| [6] (3 * 2)  |
|        |     -> return (2 * fact(1))
|        <------- [2] (2 * 1) |
|                         |   -> return (1 * fact(0))
|                         |                  |
|                         |                  -> return 1
|                         <---------- [1]   (1 * 1)
-> fact(3) = 6, (3 * 2) end result                                  
]]
```

Here you can see the chain of returns, and how each `fact` call looks. Each time there's an attempt to return, it must evaluate what the value of `fact(n - 1)` is before giving back a value. Which is why the second it tries to return `3 * fact(2)`, it evaluates `fact(2)`, but `fact(2)` will have to evaluate `fact(1)`, and `fact(1)` will have to evaluate `fact(0)`. The second that chain breaks by returning 1, it goes back up each return and will "insert" the result of that `fact` call and multiply it. I tried to show this as best I could, the return statements evaluated in parentheses, the result in square brackets \[X] and a display to show the chain of where it's inserted/used as the multiplier in the above return.

Another example of recursion would be a Fibonacci sequence:

```lua
function fib(n)
    if n < 3 then
        return 1
    end
    return fib(n-1) + fib(n-2)
end
```

Here, it will calculate n-1 + n-2 until both `n`s reach a value which is less than 3. Each of these `fib` calls chain out like `fact` did, each call must be evaluated before it can be returned for usage.

```lua
fib(5)
--[[
fib(5) | Result: 5
  |              ^
  |              |
  |              ----------------------|
  --> return fib(4) + fib(3)  | (3+2) [5]
                | ^     ^  |
                | |     |  --->  return fib(2) + fib(1)    | (1+1) [2]
                | |     --------------------------------------------|
                | |
                | -------------------------------------|
                ---> return fib(3) + fib(2)   | (2+1) [3]
                             ^  |      ^ |                                  
                             |  |      | -> return 1   [1]
                             |  |      -----------------|
                             |  |
                             |  -> return fib(2) + fib(1)    | (1+1)  [2]
                             |              ^ |      ^ |               |
                             |              | |      | -> return 1 [1] |
                             |              | |      ---------------|  |
                             |              | -> return 1 [1]          |
                             |              ---------------|           |
                             ------------------------------------------|
  ]] 
```

Again, the evaluation is in parentheses, the result is in square brackets and moves back up the chain. Reading this diagram, you go bottom-right, then follow the square brackets back up the chain, up-left.


# Metatables

Metatables are the underlying implementation of objects in Lua, they define custom behaviors such as addition between 2 objects, subtraction, accessing the value, etc.

Each of those are called metamethods, and they all begin with `__`.

All metamethods (Lua 5.1)

```lua
       __eq :     Equality      :  a == b
       __le :     Less than     :  a < b
       __ge :   Greater than    :  a > b
      __add :     Addition      :  a + b
      __sub :    Subtraction    :  a - b
      __mul :   Multiplication  :  a * b
      __div :     Division      :  a / b
      __pow :   Exponentation   :  a ^ b
      __unm :     Negation      :  -a
      __mod :      Modulus      :  a % b
   __concat :   Concatenation   :  a .. b
__metatable :     Metatable     :  getmetatable(a)
     __call :       Call        :  table()
    __index :     Indexing      :  table.x | table['x']
 __newindex :     New Index     :  table.x = 'abc'
     __mode :  Weak References  :  mt.__mode = 'k'
 __tostring : String Conversion :  tostring(a)
```

By default whenever you have a string, it has a metatable attached to it as you can see here:

```lua
local s = "abc"

print(getmetatable(s)) -- {__index = table: 0x56458af94c30}

for k, v in pairs(getmetatable(s).__index) do
	print(k, v)
end
```

When attempting to index the string, it instead returns the `string` library table. Which is why if you run this code, you'll see the `__index` of the metatable print this out:

```
dump	function: 0x557e9eddcba0
byte	function: 0x557e9eddcd70
reverse	function: 0x557e9eddba30
lower	function: 0x557e9eddbcd0
gsub	function: 0x557e9eddd810
upper	function: 0x557e9eddb980
sub	    function: 0x557e9eddcc50
match	function: 0x557e9eddd7f0
gmatch	function: 0x557e9eddc000
rep	    function: 0x557e9eddbae0
len	    function: 0x557e9eddbc70
char	function: 0x557e9eddc060
format	function: 0x557e9eddc1c0
find	function: 0x557e9eddd800
```

You can directly access these by indexing the string directly, instead of going through the string library:

```lua
local s = "abc"
print(s.len(s)) -- 3
print(s:len()) -- 3
```

The second print uses the `:` syntactic sugar, both are equivalent, but the second is preferred for shorter code. The left hand of the `:` will be inserted as the first argument to `string.len`, and will result in the equivalent code: `string.len(s)`.

You can create your own tables and define metatables for them to do as you'd like, like so:

```lua
local t = {1, 2, 3}

print(tostring(t)) -- table: 0x55b410c31620

setmetatable(t, {
    __tostring = function(self)
        return table.concat(self, ', ')
    end
})

print(tostring(t)) -- __tostring invoked, output is 1, 2, 3
```

Here we define a custom metamethod for the `tostring` function for the table, which instead calls table.concat to concatenate all table values in sequence with a separator of `,` inbetween each value.


# Weak Tables

Lua's way of memory management is running something called a garbage collector. Every garbage collection cycle, all objects that have no references is freed back up to use to the program. Weak tables are a way to let the garbage collector know that it can go ahead and free up the memory if there are no references to that object anymore.

The weakness of a table is set by the `__mode` metamethod, if the string of `__mode` contains k, the keys are weak. If it contains v, the values are weak. If it contains both (kv), both the keys and values are considered weak.

Example:

```lua
local t = {}

setmetatable(t, {__mode = 'k'})

do
    -- closure
    local key = {} -- key is the reference to this table (object)
    t[key] = 123
end

collectgarbage() -- force a garbage collection cycle
-- variable 'key' is out of scope since it was created in a closure
-- after garbage collection, the object held by key is removed from 't'

for k, v in pairs(t) do
    print(k, v)
end

-- prints nothing

do
    key = {}
    t[key] = 123
end

collectgarbage()
-- key is still valid since it's a global variable

for k, v in pairs(t) do
    print(k, v)
end

-- prints table: 0x56144f2e36e0 123
```


# Memoization

Memoization is a programming technique to basically "cache" expensive procedures or operations in order to avoid evaluating their results again.

Take this function for example, to generate a character list starting from lowercase chars up to a certain character code:

```lua
local mem = {}

function generateCharlist(n)
	if mem[n] then
		return mem[n]
	end
	local str = ''
	for i = 97, 97+n do -- start from lowercase
		str = str .. string.char(i) -- convert number to character
	end
	mem[n] = str
	return str
end

local firstList = generateCharlist(25) -- performs the generation
local secondList = generateCharlist(25) -- uses the pre-generated value

print(firstList, secondList) -- abcdefghijklmnopqrstuvwxyz	abcdefghijklmnopqrstuvwxyz
```

Here once `generateCharlist` is called the first time, that string is generated and inserted into the `mem` table, the next time it runs with the exact same param as the first call, it will use the pre-generated value rather than having to spend the time generating it again.

Do not use that code as a good "optimized" example of that process (specifically lines 7-10), since I intended for it to perform poorly. More info about why this is awful to do can be found in the [Optimizations](/lua-guide/auxiliary/optimizations) page.


# Object-Oriented Programming

Object-Oriented Programming (shortened to OOP) is a programming paradigm to wrap up a set of variables and functions (called methods) inside of a single object. A common example of this is a "Player" in a game, each player has the same set of variable names but different values, such as health, name, etc. A `class` is the definition of the variables and methods which are used by objects created using that class.

Since Lua has no true OOP implementation such as classes, we can get quite close to OOP and still be able to create unique objects and play around with them. The way we wrap all variables and functions inside a "class" is by holding all of that data in a table. Here's an example of creating a Player class:

```lua
Player = {}

setmetatable(Player, {
	__call = function(self, name, health)
		local playerData = {
			name = name,
			health = health
		}
		return setmetatable(playerData, {__index = Player})
	end
})

function Player.getName(self)
	return self.name
end

function Player.getHealth(self)
	return self.health
end

function Player.print(self)
	print('Player "'.. self:getName() ..'": (Health: '.. self:getHealth() ..')')
end

local playerOne = Player('John', 100)
local playerTwo = Player('Jack', 150)
playerOne:print()
playerTwo:print()
```

The output of the above example results in:

```
Player "John": (Health: 100)
Player "Jack": (Health: 150)
```

Here we use the `__call`metamethod to create a definition on what happens when you call the table like it's a function. Player is defined at the top as a table, `{}`, but with the `__call` metamethod, doing `Player(name, health)`is valid. Once the `__call`metamethod is invoked, we simply take the arguments passed to it and insert it into a table. After which, we just simply return the table after using `setmetatable` to define our object's `__index`, which is used whenever we try to access the player object's table. The `__index` will hold everything inside of the Player table, but out object only holds name and health. Using `__index`, if what we're trying to access doesn't exist in the player object such as doing `playerOne.xyz`, it uses the table defined in `__index` to look in as well, if `xyz` is a key inside of Player, then that is returned.

We can see that here, there are 3 methods defined inside the Player table, which are getName, getHealth, and print. When calling `playerOne:print()`, it searches the player object which only holds `{name = 'John', health = 100}`, since `print` is not a key in our player object, it will search the `Player` table for it, and since we did define a `print` method, that will be used.

Again, `playerOne:print()` is the equivalent to `Player.print(playerOne)`, just shorter and using the `:` syntax sugar.


# Basic

### \_G

Description: Global variable that holds the global environment (all global functions/variables)

Example:

```lua
print(_G.tostring(true)) -- tostring is global, which makes it accessible via _G as well
```

### setfenv

Description: sets the environment for a function to use, rather than \_G.

Usage: setfenv(f)

Example:

```lua
function x()
    zzz.x = 5
    print() -- will not work here, the environment is not _G.
end

setfenv(x, {zzz = {x = 10}})
```

### getfenv

Description: returns the environment in use by given function or stack level, default 1.

Usage: getfenv(\[f])

Example:

```lua
function x()
    zzz.x = 5
    print() -- will not work here, the environment is not _G.
end

setfenv(x, {zzz = {x = 10}})
print(getfenv(x)) -- environment is {zzz = {x = 10}}
```

### setmetatable

Description: sets the metatable for given table

Usage: setmetatable(table, metatable)

Example:

```lua
local t = {}
setmetatable(t, {__call = print})
```

### getmetatable

Description: gets the metatable of specified table, returning the `__metatable` metamethod's value if applicable

Usage: getmetatable(table)

Example:

```lua
local t = {}
setmetatable(t, {__call = print})
print(getmetatable(t)) -- {__call = print}
setmetatable(t, {__metatable = {x = 5}})
print(getmetatable(t)) -- {x = 5}
```

### rawset

Description: sets a value in the table at specified index without invoking any metamethods

Usage: rawset(table, index, value)

Example:

```lua
local t = {}
setmetatable(t, {__newindex = function(self, k, v)
    print('Value set at index '.. tostring(k) ..' to value '.. tostring(v))
end})

t.x = 5 -- Value set at index x to value 5
rawset(t, 'xx', 50) -- prints nothing, __newindex is not be invoked
```

### rawget

Description: returns a value from a table at given index without invoking any metamethods

Usage: rawget(table, index)

Example:

```lua
local t = {}
setmetatable(t, {__index = function(self, k, v)
    print('Accessing value at index '.. tostring(k))
end})

print(t.x) -- Accessing value at index x
print(rawget(t, 'x')) -- nothing, __index is not invoked
```

### rawequal

Description: compares two values using == without invoking any metamethod

Usage: rawequal(v1, v2)

Example:

```lua
local mt = {__eq = function(a, b)
    print('Checking equality ( '.. tostring(a) ..' vs '.. tostring(b) ..' )')
    return rawequal(a, b)
end}

local t = {}
setmetatable(t, mt)

local t2 = {}
setmetatable(t2, mt)

print(t == t2) -- Checking equality ( table: 00f28b00 vs table: 00f28a10 )
print(rawequal(t, t2)) -- nothing, __eq is not invoked
```

### pairs

Description: iterator to traverse over a table in any order possible

Usage: pairs(t)

Example:

```lua
local t = {1, 2, 3}
for k, v in pairs(t) do
    print(k, v)
end
```

### ipairs

Description: iterator to traverse over a table in sequence

Usage: ipairs(t)

Example:

```lua
local t = {1, 2, 3}
for k, v in ipairs(t) do
    print(k, v)
end
```

### loadstring

Description: loads a Lua chunk

Usage: loadstring(string \[, chunkName])

Example:

```lua
local f = loadstring([[return function() print(123) end]])
f() -- 123
```

### loadfile

Description: loads a Lua chunk from specified file, or from standard input if filename is not specified

Usage: loadfile(\[filename])

Example:

```lua
-- x.lua
return function() print(123) end

-- other file.lua
local f = loadfile("x.lua")
f() -- 123
```

### next

Description: returns the next key, value pair in `table` starting from specified index, otherwise `index`, is nil

Usage: next(table \[, index])

Example:

```lua
local t = {1, 2, 3}
print(next(t, 2)) -- 3, 3
print(next(t)) -- 1, 1
```

### pcall

Description: calls a function in a protected state, returning any errors if they happen, otherwise returns true if successful plus the returned values from `f`

Usage: pcall(f, ...)

Example:

```lua
function x(n)
    return x + n
end

local success, ret = pcall(x, 5)
print(success, ret) -- false    C:\Users\user\lua_file.lua:2: attempt to perform arithmetic on a function value (global 'x')
```

### xpcall

Description: calls a function in a protected state, using `err` as the error handler and returning true if no errors happen, otherwise returns false plus the result from `err`

Usage: xpcall(f, err)

Example:

```lua
function x(n)
    return x + n
end

local function x_error_handler(error)
	print(error)
	return 123
end

local success, ret = xpcall(x, x_error_handler)
print(success, ret)
```

Output:

```
C:\Users\user\lua_file.lua:2: attempt to perform arithmetic on a function value (global 'x')
false 123
```

### unpack

Description: unpacks a table in sequence, starting from i and ending with j (1, #table respectively by default), returning all values from it

Usage: unpack(table \[, i \[, j]])

Example:

```lua
local t = {1, 2, 3, 4, 5}
print(unpack(t)) -- 1, 2, 3, 4, 5
print(unpack(t, 2, 4)) -- 2, 3, 4
```

### type

Description: returns the data type of given value

Usage: type(value)

Example:

```lua
print(type(123)) -- number
print(type({})) -- table
print(type(nil)) -- nil
print(type('')) -- string
print(type(true)) -- boolean
```

### tonumber

Description: converts value to a number if possible

Usage: tonumber(val \[,base])

Example:

```lua
local x = '5'
print(tonumber(x)) -- 5
print(type(tonumber(x))) -- number
print(type(x)) -- string
```

### tostring

Description: converts value to a string

Usage: tostring(val)

Example:

```lua
print(tostring({})) -- table: 00ee88a8
print(tostring(5)) -- 5

print('This is a boolean: '.. tostring(true)) -- This is a boolean: true
```


# String


# Table

### table.concat

Description: concatenates all strings in the table, starting from i, ending with j (default 1, #t respectively), separating with the `separator` value if defined, otherwise there is no separation.

Usage: table.concat(table \[, separator \[, i \[, j]]])

Example:

```lua
local t = {'a', 'b', 'c'}
print(table.concat(t)) -- abc
print(table.concat(t, ', ')) -- a, b, c
print(table.concat(t, ', ', 2)) -- b, c
print(table.concat(t, nil, 1, 2)) -- ab
```

### table.insert

Description: inserts a value to the end of the table, or at `pos`

Usage: table.insert(table, \[pos,] value)

Example:

```lua
local t = {'a', 'b', 'c'}
table.insert(t, 'd') -- {'a', 'b', 'c', 'd'}
table.insert(t, 3, 'f') -- {'a', 'b', 'f', 'c', 'd'}
```

### table.maxn

Description: returns the highest numerical index found in the table (different from true size)

Usage: table.maxn(table)

Example:

```lua
local t = {1, 2, 3, 4, 5, 100, 3, 77, 275}
print(table.maxn(t)) -- 9

t = {1, 2, 3, 4, 5, 100, 3, 77, 275, nil, nil, 177, ['a'] = 5}
print(table.maxn(t)) -- 12, 'a' is not a numerical index
```

### table.remove

Description: removes a value from the table at the end, or at `pos`

Usage: table.remove(table \[, pos])

Example:

```lua
local t = {1, 2, 3, 4, 5}
table.remove(t) -- {1, 2, 3, 4}
table.remove(t, 2) -- {1, 3, 4}
```

### table.sort

Description: sorts table with given `comp` (comparison) function, if not given, `<` is used by default, which results in least to greatest.

Usage: table.sort(table \[, comp])

Example:

```lua
local t = {5, 26, 7, 1, 400}
table.sort(t) -- {1, 5, 7, 26, 400}

local t = {5, 26, 7, 1, 400}
table.sort(t, function(a, b) return a > b end) -- {400, 26, 7, 5, 1}
```


# Math


# IO


# Coroutine


# OS (Operating System)


# Package


# Optimizations

### String concatenation

Lua's garbage collector will run when it detects if too much memory is in use by the program. When using the string concat (..) operator, the result is a completely new string, and the old one is garbage if you're reassigning (which results in the old string having no reference) `x = x .. "\n"`, the garbage collector will eventually run and collect this string. When you're concatenating large strings together over and over again (like in a loop) that will add up quickly and force the garbage collector to run and will slow down code by a lot the larger those strings are.

```lua
local result = ''

for line in io.lines('large_file.txt') do
    result = result .. line -- old 'result' is now garbage
end
```

This code will take much longer to run because the more and more lines concatenated to result, the larger result is, and the larger result is, the more memory is used and forces the garbage collector to run.

A solution to speed this process up is by putting all strings into a table and running `table.concat` on it:

```lua
local strings = {}

for line in io.lines('large_file.txt') do
    table.insert(strings, line)
end

local result = table.concat(strings, '\n')
```

This will be much faster than manually concatenating all strings (table.concat uses a C implementation rather than Lua)

{% hint style="info" %}
Before getting into the rest of the optimizations, you really don't need to be using these unless you're **really** trying to get performance out of a hugely expensive program or function call.
{% endhint %}

### Squeezing performance from table indexing

When indexing a table to retrieve a value, it takes time. Although a small amount of time, it can result in a decent chunk of time if you're running a function which takes a long time to finish regardless of this optimization. Calling lib functions such as string.len, table.concat, etc. all take time since they're a part of libraries which are tables. This is a way to store those functions without having to retrieve them over and over again:

```lua
local stringLen = string.len
```

Now we the function retrieved and stored in stringLen rather than having to retrieve it over and over again from the string library. Calling stringLen in an expensive function will increase performance by a lot.

```lua
local stringLen = string.len
local tostring = tostring

function f()
	for i = 1, 10000 do
		stringLen(tostring(i))
	end
end

function f_2()
	for i = 1, 10000 do
		string.len(tostring(i))
	end
end
```

Between these two functions, `f` will perform faster than `f_2` because both functions used are saved in a local variable rather than getting retrieved from `_G`, which saves time over a long period of time.

### Adding values to tables

Lua provides a default function to insert a value into a table (table.insert), but, using this function takes significantly longer if you're just trying to insert a value into the next index that isn't used. If you're just looking to insert a new value into the next available index, this will perform much faster:

```lua
local t = {}
t[#t+1] = 'a'
t[#t+1] = 'b'
```

Here we just calculate the next index by using the current size + 1 (#t + 1) and insert a value into that new index.

If you're using a loop to insert new values, keeping track of the index manually will be faster than using the length operator each iteration:

```lua
local strings = {'a', 'b', 'c'}
local toInsert = {'d', 'e', 'f', 'g'}

local index = #strings -- current size
for _, str in ipairs(toInsert) do
    index = index + 1
    strings[index] = str
end
```

Since we keep track of the index manually and add 1 each iteration, the length operator doesn't need to be used every single time which would add up after a while.


# Benchmarking

With `os.clock`, you can compute (just about) the CPU time taken to execute a chunk of code.

```lua
local start = os.clock() -- save current CPU time

for i = 1, 100000 do
    -- do something
end

print('Time taken: '.. (os.clock() - start) ..' seconds.')
```

By saving the time before starting the code and subtracting the before from the time after it executes, you get an approximate amount of seconds taken to execute that chunk of code.

Here's a benchmarking function to help with determining the performance of code:

```lua
do
    local units = {
        ['seconds'] = 1,
        ['milliseconds'] = 1000,
        ['microseconds'] = 1000000,
        ['nanoseconds'] = 1000000000
    }

    function benchmark(unit, decPlaces, n, f, ...)
        local elapsed = 0
        local multiplier = units[unit]
        for i = 1, n do
            local now = os.clock()
            f(...)
            elapsed = elapsed + (os.clock() - now)
        end
        print(string.format('Benchmark results:\n  - %d function calls\n  - %.'.. decPlaces ..'f %s elapsed\n  - %.'.. decPlaces ..'f %s avg execution time.', n, elapsed * multiplier, unit, (elapsed / n) * multiplier, unit))
    end
end
```

* `unit`: Unit of time to show the result in ('seconds', 'milliseconds', 'microseconds', or 'nanoseconds')
* `decPlaces`: Number of decimal places to use when showing the elapsed time
* `n`: Number of times to run the function
* `f`: Function to run
* `...`: Arguments passed to function `f`

Example of using it from the previous page:

```lua
local stringLen = string.len
local tostring = tostring

function f()
	for i = 1, 10000 do
		stringLen(tostring(i))
	end
end

function f_2()
	for i = 1, 10000 do
		string.len(tostring(i))
	end
end

benchmark('milliseconds', 2, 50, f)
benchmark('milliseconds', 2, 50, f_2)
```

Output of the above:

```
Benchmark results:
  - 50 function calls
  - 868.86 milliseconds elapsed
  - 17.38 milliseconds avg execution time.
Benchmark results:
  - 50 function calls
  - 874.66 milliseconds elapsed
  - 17.49 milliseconds avg execution time.
```


# Errors

### List of errors

#### Attempt to call a nil value

Description: calling a function that doesn't exist

Example:

```lua
printtt("abc") -- printtt is not a function

test() -- calling before it's defined, same error

function test() end

test() -- works
```

#### Unexpected symbol near 'something'

Description: an invalid character is placed next to a value/keyword/variable/function call

```lua
function abc()) end -- unexpected symbol near ')'

local a = 5
a l= 15 -- unexpected symbol near 'l'

local a = 5] -- unexpected symbol near ']'
```

#### Attempt to index global 'variable' (a nil value)

Description: indexing via `[key]` or `.key` for a variable that doesn't exist

Example:

```lua
abc.x = 5 -- abc is nil, error

abc = {} -- abc defined here

abc.x = 5 -- works

xyz['x'] = 'abc' -- xyz is nil, error
```

#### Attempt to perform arithmetic on a nil value

Description: performing arithmetic (\*, /, -, +, %, ^) on a nil value

Example:

```lua
print(xyz + 5) -- error, xyz not defined
a = a + 5 -- error, a not defined
```

#### Attempt to perform arithmetic on field '?' (a nil value)

Description: performing arithmetic (\*, /, -, +, %, ^) on a nil value

Example:

```lua
local t = {}
t.x = t.x + 5
```

#### Attempt to compare nil with \<TYPE>

Description: using a comparison operator (<, >, \~=, ==, >=, <=) in which one side is a nil value

Example:

```lua
local x = 5
print(x < y) -- y is not defined
```

#### Malformed number near \<NUMBER>

Description: the number has an invalid character next to it

Example:

```lua
print(12345aaa) -- aaa makes it a malformed number
```

#### Unfinished capture | Malformed pattern

Description: the pattern is missing a closing `)`, or a closing `]`

Example:

```lua
print(string.match('ABC', '(')) -- unfinished capture
print(string.match('ABC', '[')) -- malformed pattern
```

### Interpreting errors

When you get an error, Lua provides a stack trace showing you where it originates from, where the error occurs, the function calls that led to the error, and the line number of where it occurred.

A general error will look like this:

```
file_location:LINE NUMBER: error message
stack traceback:
    file_location:LINE NUMBER: in <local/function> 'FUNC'
    file_location:LINE NUMBER: in main chunk
    [C]: in ?
```

Here's an example:

```
C:\Users\user\lua_file.lua:5: attempt to perform arithmetic on a nil value (field 'x')
stack traceback:
	C:\Users\user\lua_file.lua:5: in local 'c'
	C:\Users\user\lua_file.lua:7: in local 'b'
	C:\Users\user\lua_file.lua:9: in function 'a'
	C:\Users\user\lua_file.lua:12: in main chunk
	[C]: in ?
```

The code that resulted in this error is:

```lua
function a()
	local function b()
		local function c()
			local t = {}
			t.x = t.x + 5
		end
		c()
	end
	b()
end

a()
```

Here you can see the line number `5` after the file location, which tells us where the exact line with the code that resulted in the error. The stack traceback shows the functions that were called that led up to that.

First, function `a` is called at line 12, then function `b` is called at line 9 inside of `a`, then `c` is called at line 7 inside of function `b`, and finally at line 5, the error occurs inside of function `c`.

A note to add is that comments can offset the line number and make it appear as the error is in a line that doesn't exist or doesn't look like an error,


# Debugging

When you're not sure why your code doesn't work or some statements aren't executing, a good method of making sure where you're getting to is by debugging with print statements.

This method will allow you to see how far your function or code gets before the error or something you're expecting doesn't happen, and lets you pinpoint what you need to fix.

```lua
function swap(a)
	return not a
end

function doRandomStuff(a)
	a = swap(a)
	return swap(a)
end

function test(a)
	a = doRandomStuff(a)
	if a then
		print(123)
	end
end

test(true)
```

Here for example, we swap the boolean's value to the opposite, and if a is true we're supposed to print 123. But the problem is, swap happens twice instead of returning the 1st time it's swapped (which is the "example" error in this case. Here, we can add prints to see what's going on to see why we can't print 123:

```lua
function swap(a)
	return not a
end

function doRandomStuff(a)
	print('doRandomStuff - "a" value: '.. tostring(a))
	a = swap(a)
	print('doRandomStuff - "a" swapped value: '.. tostring(a))
	return swap(a)
end

function test(a)
	print('test - initial "a" value: '.. tostring(a))
	a = doRandomStuff(a)
	if a then
		print(123)
	end
end

test(false)
```

This current code will print:

```
test - initial "a" value: false
doRandomStuff - "a" value: false
doRandomStuff - "a" swapped value: true
```

We can see that we're obviously getting an expected value, after reassigning `a` to swap(a), which is the value we're supposed to use, but instead we swap it a 2nd time giving us back the original value (false->true->false). From here we know that the error is that we've swapped the boolean twice when it's supposed to be swapped once, so all we need to do is return `a` instead of return `swap(a)`.

```lua
function swap(a)
	return not a
end

function doRandomStuff(a)
	a = swap(a)
	return a
end

function test(a)
	a = doRandomStuff(a)
	if a then
		print(123)
	end
end

test(false)
```

Now the code works as intended, and prints 123.


