Getting started

LuaScripting uses Lua 5.2 with NLua to communicate with .NET. This guide assumes basic knowledge of Lua and only concentrates on how to write NLua scripts.

Script structure

LuaScripting loads and runs all scripts from BepInEx/lua_scripts. Each Lua script is run in a separate state, so they don’t share any variables with each other.

In addition, you can load additional Lua files with a require directive. In that case additional scripts are loaded from BepInEx/lua_scripts/requires. Thus the following require statement

1
require "foo"

will try to load BepInEx/lua_scripts/requires/foo.lua.

Registering scripts

While it is not mandatory, it is recommended to register a script to the script manager provided by LuaScripting. Registering a script is as simple as calling register_script() in some place of the script:

1
2
3
4
5
6
Script = {}
register_script(Script, {
    name = "Example Script",
    version = "1.0.0.0",
    description = "This is an example script"
})

This will register a script to LuaScripting and allow to receive some of MonoBehaviour events. To do this, add one or more functions to your Script object with the following names:

  • Awake
  • Start
  • Update
  • FixedUpdate
  • LateUpdate
  • OnGUI
  • OnDestroy

Note

On script reload, OnDestroy will be called right before the old script version is unloaded. In addition Awake and Start will both be called on the new script after script has been reloaded.

Use this to unload and load resources when the script is being reloaded.

Example of script using callbacks of MonoBehaviour
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Script = {}

function Script:Awake()
    print("Called MonoBehaviour.Awake()")
end

function Script:Update()
    print("Called each frame")
end

function Script:OnDestroy()
    print("Script is being unloaded (either game closing or script being reloaded)!")
end

register_script(Script, {
    name = "Example Script",
    version = "1.0.0.0",
    description = "This is an example script"
})