This video is part 3 of a series:

  1. Lua Style Guide
    1. Formatting with StyLua
  2. Lua Scripting Best Practices
  3. Organizing Lua Code With Modules ← You Are Here
  4. Module Best Practices

Introduction

Avoid adding new lua game logic directly to Trigger.lua.txt. Instead, write new game logic in a separate file (called a **module** in lua), and import the functionality into Trigger.lua.txt

To create a module, make a new file in your Scripts folder, add functions and variables to it, and return it at the end of the file:

-- file MathModule.lua.txt

local MathModule = {
	pi = 3.14
}

function MathModule:Sum(number_a, number_b)
	return number_a + number_b
end

return MathModule

Then in some other file, import the module with require :

-- file Trigger.lua.txt

local MathModule = require("MathModule")

-- prints "3.14"
DCEI.LogMessage(MathModule.pi)

local sum = MathModule:Sum(2, 2)

-- prints "4"
DCEI.LogMessage(sum)

Module Naming and Organization

Module Best Practices

It’s helpful to use a standard module structure to increase readability for yourself and other designers. Let’s go through an example module top to bottom. In this case a designer is coding a module to arrange units in a battle scene like this: