In this tutorial, we will be implementing a score counter that increments when an enemy is killed, a trigger to respawn enemies, and casting an ability with your hero.

This tutorial will cover:

1. Creating Functions


So far we’ve used the LogMessage() and CreateUnit() DCEI functions but we can create our own functions too. This lets us create re-usable pieces of code with customizable behavior (you can read more about functions here).

Let’s write a function that spawns an enemy unit from just one “point” parameter (Lua supports passing arrays as parameters). In Lua, parameter names are arbitrary and untyped. We called ours “point” but we could call it whatever we wanted. Descriptive names are generally recommended.

Write the following function right below the -- TRIGGERS section.

-- TRIGGERS
function SpawnEnemyUnitAtPoint(point)
    DCEI.CreateUnit(-1, -1, enemy_unit_name, point[1], point[2])
end

If you SAVE and hit play, nothing new will happen. This is because functions must be called to be executed. Let’s refactor our for loop to use our new function. At this point your complete trigger file should look like this:

--- LIBRARIES

-- VARIABLES

-- TRIGGERS

-- INITIALIZATION- VARIABLES
local hero_unit_name = DCEI.Unit("Hero IceMage")
local enemy_unit_name = DCEI.Unit("Standard MeleeUnit")
local enemy_points = {
    {20, 14},
    {21, 16},
    {20, 18}
}

-- TRIGGERS
local function SpawnEnemyUnitAtPoint(point)
    DCEI.CreateUnit(-1, -1, enemy_unit_name, point[1], point[2])
end

DCEI.LogMessage("Hello Lua!")

DCEI.CreateUnit(1, 1, hero_unit_name, 16, 16)

for key, value in ipairs(enemy_points) do
    SpawnEnemyUnitAtPoint(value)
end

Note that local functions must be defined above where it is called in the script. This is because Lua executes line by line from the top down. If you tried to declare your function after the for loop, you’ll get a script error.

2. Organizing Your Script With Comments


As you’ve seen so far, we’ve been separating our Variables and Triggers in separate sections. As your project grows, keeping your game logic organized is an important consideration for keeping development running smoothly.

I like to split my trigger files into four main sections: libraries, global variables, triggers, and initialization. We can use comments to split our trigger files into multiple sections that are easier to keep track of.

-- LIBRARIES

-- VARIABLES

-- TRIGGERS

-- INITIALIZATION

To write comments, start a line with -- Comment text. Commented lines aren’t run by the game and are used to make the script more understandable. Block or multiline comments can be created with --[[ ]]:

--[[
    Block comment text that
    can span multiple lines
]]

Comments can also be used to add notes about a specific piece of code or even temporarily disable/enable code for testing. For practice, let’s comment out the DCEI.LogMessage("Hello Lua!") since we don’t need it anymore. If done correctly it should change color.