Color
- Color
Functions
Debug
- Debug
Functions
Event
GameSpeed
- GameSpeed
Functions
GetRandomPointInMapOptions
- GetRandomPointInMapOptions
Properties
Input
- Input
Functions
Point
PresentationDebug
- PresentationDebug
Functions
PresentationEvent
Random
- Random
Functions
SimulationCore
- SimulationCore
Functions
String
Table
Timer
TimerOptions
Unit
Util
actor_message
behaviorName
effectName
Color
HexToRGBA
function Color.HexToRGBA(hex: string)
-> table
Returns a table
array of RGBA values (0 - 255) from a hexadecimal string. If no alpha value is supplied, the returned color will have full opacity.
Example usage:
local hex_color = "#f17aed"
local magenta = Core.Color.HexToRGBA(hex_color)
-- magenta = {241, 122, 237, 255}
local layout = GMUI.Layout.New({
parent = GMUI.ui.Root,
name = "Standard/Button/Button",
})
DCEI.SetFrameImageColor(
layout.Button,
{ r = magenta[1] / 255, g = magenta[2] / 255, b = magenta[3] / 255, a = magenta[4] / 255 }
)
@param hex
— A RGBA hex color value. e.g. green is "#00ff00ff", red is "#ff0000ff", blue is "#0000ffff"
@return — {r, g, b, a} values 0 - 255
HexToValues
function Color.HexToValues(hex: string)
-> table
Returns a table
array of RGBA values (0 - 1) from a hexadecimal string. If no alpha value is supplied, the returned color will have full opacity.
Example Usage
local hex_color = "#f17aed"
local magenta = Core.Color.HexToValues(hex_color)
-- magenta = {0.95, 0.48, 0.93, 1}
local layout = GMUI.Layout.New({
parent = GMUI.ui.Root,
name = "Standard/Button/Button",
})
DCEI.SetFrameImageColor(layout.Button, { r = magenta[1], g = magenta[2], b = magenta[3], a = magenta[4] })
RGBAToHex
function Color.RGBAToHex(rgba: table)
-> ex: string
Returns a hexadecimal color value as a string
from a table
array of RGBA values. If no alpha value is supplied, the returned color will have full opacity.
Example Usage
local rgba = { 241, 122, 237 }
local magenta = Core.Color.RGBAToHex(rgba)
local tag = "<color=" .. magenta .. ">"
-- magenta = "#f17aed"
local text = tag .. "Magenta"
local label = DCEI.CreateTextFrame(GMUI.ui.Root)
DCEI.SetTextFrameText(label, text)
@param rgba
— ex {241, 122, 237}
@return ex
— f17aed
RGBAToValues
function Color.RGBAToValues(rgba: table)
-> e.g.: table
Returns a table
array of RGBA percentage values (0 - 1) from a hexadecimal string. If no alpha value is supplied, the returned color will have full opacity.
Example Usage
local rgba = { 0, 0, 0, 160 }
local faded_black = Core.Color.RGBAToValues(rgba)
-- faded_black = {0, 0, 0, 0.63}
local layout = GMUI.Layout.New({
parent = GMUI.ui.Root,
name = "Standard/Button/Button",
})
DCEI.SetFrameImageColor(
layout.Button,
{ r = faded_black[1], g = faded_black[2], b = faded_black[3], a = faded_black[4] }
)
@param rgba
— e.g. {0, 0, 0, 160} (0-255 values)
@return e.g.
— {0, 0, 0, 0.63} (0-1 values)
Debug
LogLastPresentationStackTrace
function Debug.LogLastPresentationStackTrace(message?: string)
Prints the last stored presentation stack trace to the log as an error.
@param message
— An optional message to prepend the stack trace with
Effect
Create
function Effect.Create(effect_name: string, x: number, y: number)
Creates an effect at a map point.
@param effect_name
— Name of the effect to cast. Remember to declare the effect, such as DCEI.Effect("DoNothing")
@param x
— The x position of the point to create the effect at
@param y
— The y position of the point to create the effect at
Event
RegisterSimulationEvent
function Event.RegisterSimulationEvent(event_id: string, callback_function: function)
Registers a simulation event with the given id and callback function. This callback function can be triggered from
presentation layer using Core.Event.SendSimulationEvent().
SendPresentationEvent
function Event.SendPresentationEvent(event_id: string, data?: any, context?: function|table)
Send an event from simulation layer to presentation. Events need to be added with Core.Event.RegisterPresentationEvent(event_id, callback)
first.
The callback will be called using the data and context passed with this function as its first and second parameters.
The simulation stack trace will be passed as a third parameter, if enabled using Core.Debug.EnableCrossLayerStackTracing().
GameSpeed
Get
function GameSpeed.Get()
-> number
Returns the current game speed (as set by GameSpeed.Set()
/GameSpeed.Clear()
.
Example Usage
DCEI.LogMessage("Game Speed is " .. Core.GameSpeed.Get())
ResetToDefaultValue
function GameSpeed.ResetToDefaultValue()
Resets the current game speed to 1
by clearing the game's update frequency and speed factor.
Example Usage
Core.GameSpeed.ResetToDefaultValue()
Set
function GameSpeed.Set(speed: number)
Sets the game speed. Game speed is clamped between 0
and 3
.
This function uses a combination of DCEI.SetUpdateFrequency()
and DCEI.SetSpeedFactor()
to achieve the specified speed in one handy function.
Example Usage
local game_speed = Core.GameSpeed.Get()
local button = DCEI.CreateButtonFrame(GMUI.ui.Root)
DCEI.SetFrameSize(button, 128, 128)
local label = DCEI.CreateTextFrame(button)
DCEI.SetTextFrameText(label, game_speed)
local function CycleGameSpeed()
-- cycles the game speed between 1, 2, and 3
game_speed = Core.Math.Cycle(game_speed, 1, 1, 3)
Core.GameSpeed.Set(game_speed)
DCEI.SetTextFrameText(label, game_speed)
end
DCEI.SetOnClickCallback(button, CycleGameSpeed)
GameTimer
Unlike Real
and Os
timers, Game
timers are affected by game speed.
By default, Game timers update every 0.0625 seconds (this can be overridden with Core.Timer.SetGlobalTickRate
).
New
function GameTimer.New(args: any)
-> GameTimer
GetRandomPointInMapOptions
padding
number
Shrink the random point area with specified padding number. Default 2
Input
HookupJoystick
function Input.HookupJoystick(unit: Unit)
Hooks up a joystick to a unit and hides the joystick offscreen. This function is intended to quickly test unit movement and provides no customization options.
To create your own joystick movement system, see the Joystick Events.
Example Usage
local unit_type = DCEI.Unit("Standard MeleeUnit")
local unit = DCEI.CreateUnit(1, 1, unit_type, 16, 16)
Core.Input.HookupJoystick(unit)
@param unit
— A unit instance
Math
Clamp
function Math.Clamp(n: number, min: number, max: number)
-> result: number
Clamps a number between the min
and max
values.
Example Usage
local values = {-10, 7, 23}
for index, value in ipairs(values) do
values[index] = Core.Math.Clamp(value, 1, 10)
end
-- values = {1, 7, 10}
@param n
— number to clamp
@param min
— minimum value (values lower than the minimum will be increased to the minimum)
@param max
— maximum value (values higher than the maximum will be decreased to the maximum value)
@return result
— n after being clamped to the min/max
Cycle
function Math.Cycle(value: number, increment: number, min: number, max: number)
-> number
Increments a value while keeping it in the given range. If the value would be greater than the max
value, it is reset to the min
instead.
Example Usage
local game_speed = Core.GameSpeed.Get()
local button = DCEI.CreateButtonFrame(GMUI.ui.Root)
DCEI.SetFrameSize(button, 128, 128)
local label = DCEI.CreateTextFrame(button)
DCEI.SetTextFrameText(label, game_speed)
local function CycleGameSpeed()
-- cycles the game speed between 1, 2, and 3
game_speed = Core.Math.Cycle(game_speed, 1, 1, 3)
Core.GameSpeed.Set(game_speed)
DCEI.SetTextFrameText(label, game_speed)
end
DCEI.SetOnClickCallback(button, CycleGameSpeed)
IsInt
function Math.IsInt(n: number)
-> boolean
Returns true
if a number is an integer.
Example Usage
IsInt(23)
-- true
IsInt(23.4)
-- false
Lerp
function Math.Lerp(start: number, finish: number, fraction: number)
-> number
Linearly interpolates between start
and finish
number values using the specified fraction
(0 - 1).
Example Usage
local start = 1
local finish = 255
Core.Math.Lerp(start, finish, 0.5)
-- returns midpoint value of 128
Core.Math.Lerp(start, finish, 0.75)
-- returns 75% interpolation of 191.5
Round
function Math.Round(n: number, decimals?: number)
-> number
Rounds a floating point value to the number of decimals
specified. If no decimals
value is given, the number will be rounded to the nearest whole number.
Example Usage
Core.Math.Round(1/3)
-- returns 0
Core.Math.Round(2/3)
-- returns 1
local decimals = 2
Core.Math.Round(2/3, decimals)
-- returns 0.67
atan2
function Math.atan2(y: number, x: number)
-> number
Returns the arc tangent of x and y as a number
in radians.
Example Usage
local v = Core.Point.GetVectorBetweenPoints(p1, p2)
local angle_between_points = Core.Math.atan2(v.y, v.x)
OsTimer
Similar to Real
timers, Os
timers are not affected by game speed.
Os
timers update every 1.0 seconds, using the precision of os.time()
. If the game is running in the background (ie, on mobile devices), Os timers will update when the game is moved to the foreground and update based on the time that passed. If a timer would have expired while the game was running in the background, it will instead expire on the first frame after the game is resumed. This makes Os timers suitable for classic mobile game timers. Note that since Os timers rely on the device's system clock, they can be manipulated by changing the device's system clock.
New
function OsTimer.New(args: any)
-> OsTimer
Point
GetAngleBetweenPoints
function Point.GetAngleBetweenPoints(p1: PointObj, p2: PointObj)
-> number
Returns the angle between two points in degrees. The result will be between -180
and 180
as follows:
90
|
180____|____ 0
-180 |
|
-90
Example Usage
local map_center_point = {x = 16, y = 16}
local unit_type = DCEI.Unit("Standard MeleeUnit")
local unit = DCEI.CreateUnit(1, 1, unit_type, 12, 12)
local pos = DCEI.GetUnitPosition2D(unit)
-- pos = {x = 12, y = 12}
local angle = Core.Point.GetAngleBetweenPoints(pos, map_center_point)
-- 45 degrees between spawned unit position and map center
@param p1
— e.g. {x = 12, y = 12}
@param p2
— e.g. {x = 12, y = 12}
GetArcDistanceBetweenAngles
function Point.GetArcDistanceBetweenAngles(angle1: number, angle2: number)
-> number
Returns the angle between two angles. This value will be between 0
and 180
.
Example Usage
function GetNearestFacingEnemy( unit, enemies )
local unit_pos = DCEI.GetUnitPosition2D(unit)
local unit_angle = Core.Unit.GetFacingAngle(unit)
local nearest_angle = 180
local nearest_enemy
for _, enemy in pairs(enemies) do
local enemy_pos = DCEI.GetUnitPosition2D(enemy)
local enemy_angle = Core.Point.GetAngleBetweenPoints(unit_pos, enemy_pos)
-- gets the angle between the unit-facing angle and the unit-to-enemy angle
local angle = Core.Point.GetArcDistanceBetweenAngles( unit_angle, enemy_angle )
if angle < nearest_angle then
nearest_enemy = enemy
nearest_angle = angle
end
end
return nearest_enemy
end
GetDistanceBetweenPoints
function Point.GetDistanceBetweenPoints(p1: PointObj, p2: PointObj)
-> number
Returns the distance between two points.
Example Usage
local map_center_point = {x = 16, y = 16}
local unit_type = DCEI.Unit("Standard MeleeUnit")
local unit = DCEI.CreateUnit(1, 1, unit_type, 12, 12)
local pos = DCEI.GetUnitPosition2D(unit)
-- pos = {x = 12, y = 12}
local distance = Core.Point.GetDistanceBetweenPoints(pos, map_center_point)
-- distance = 5.65
@param p1
— ex. {x = 16, y = 16}
@param p2
— ex. {x = 16, y = 16}
GetInterpolatedPoint
function Point.GetInterpolatedPoint(p1: PointObj, p2: PointObj, fraction: number)
-> table
Returns a point along the line between two points, determined by the given fraction (0 - 1).
Example Usage
local map_center_point = {x = 16, y = 16}
local unit_type = DCEI.Unit("Standard MeleeUnit")
local unit = DCEI.CreateUnit(1, 1, unit_type, 12, 12)
local pos = DCEI.GetUnitPosition2D(unit)
-- pos = {x = 12, y = 12}
local p1 = Core.Point.GetInterpolatedPoint(pos, map_center_point, 0)
-- p1 = {x = 12, y = 12}, the same as pos
local p2 = Core.Point.GetInterpolatedPoint(pos, map_center_point, 1)
-- p2 = {x = 16, y = 16}, the same as map_center_point
local p3 = Core.Point.GetInterpolatedPoint(pos, map_center_point, 0.5)
-- p3 = {x = 14, y = 14}, the midpoint between the two
@param p1
— ex. {x = 16, y = 16}
@param p2
— ex. {x = 16, y = 16}
GetPointFromXY
function Point.GetPointFromXY(x: any, y: any)
-> table
Returns a point from x
and y
coordinates.
Example Usage
local map_center_point = Core.Point.GetPointFromXY(16, 16)
-- map_center_point = {x = 16, y = 16}
GetPointWithPolarOffset
function Point.GetPointWithPolarOffset(x: number, y: number, angle: number, distance: number)
-> table
Returns a point offset by a distance
towards an angle
(in degrees).
Example Usage
local pos = DCEI.GetUnitPosition2D(unit)
local facing = Core.Unit.GetFacingAngle(unit)
local distance = 4
local forward_point = Core.Point.GetPointWithPolarOffset( pos.x, pos.y, facing, angle)
-- teleports a unit forward a distance of 4
DCEI.SetUnitPosition2D(unit, forward_point.x, forward_point.y)
GetRandomPointInMap
function Point.GetRandomPointInMap(args: GetRandomPointInMapOptions)
-> table
Returns a random point within the map bounds. Has table args
with padding
option (default 2
) to shrink the random point area.
Example Usage
-- if the map has dimensions of 32 x 32 the point will be generated between (4, 4) and (27, 27)
-- note that for a map of 32 x 32 the playable dimensions will span (0, 0) to (31, 31)
local options = { padding = 2 }
local pos = Core.Point.GetRandomPointInMap(options)
local unit_type = DCEI.Unit("Standard MeleeUnit")
DCEI.CreateUnit(1, 1, unit_type, pos.x, pos.y)
GetVectorBetweenPoints
function Point.GetVectorBetweenPoints(p1: PointObj, p2: PointObj)
-> table
Returns an xy vector between two points.
Example Usage
local v = Core.Point.GetVectorBetweenPoints(p1, p2)
local angle_between_points = Math.atan2(v.y, v.x)
@param p1
— ex. {x = 16, y = 16}
@param p2
— ex. {x = 16, y = 16}
GetVectorFromAngle
function Point.GetVectorFromAngle(angle: number)
-> table
Returns an xy vector from an angle (in degrees).
Example Usage
local v = Core.Point.GetVectorFromAngle(45)
-- v is {x = 0.7, y = 0.7}
DCEI.TurnUnitTowardsWithDuration(unit, v.x, v.y, 1)
x
number
x value of the point
y
number
y value of the point
PresentationDebug
LogLastSimulationStackTrace
function PresentationDebug.LogLastSimulationStackTrace(message?: string)
Prints the last stored simulation stack trace to the log as an error.
@param message
— An optional message to prepend the stack trace with
PresentationEvent
RegisterPresentationEvent
function PresentationEvent.RegisterPresentationEvent(event_id: string, callback_function: function)
Registers a presentation event with the given id and callback function. This callback function can be triggered from
simulation layer using Core.Event.SendPresentationEvent().
SendSimulationEvent
function PresentationEvent.SendSimulationEvent(event_id: string, data?: any, context?: function|table)
Send an event from presentation layer to simulation. Events need to be added with Core.Event.RegisterSimulationEvent(event_id, callback)
first.
The callback will be called using the data and context passed with this function as its first and second parameters.
The simulation stack trace will be passed as a third parameter, if enabled using Core.Debug.EnableCrossLayerStackTracing().
Random
GetInteger
function Random.GetInteger(min: any, max: any)
-> number
Returns a seed-based random integer. The random number generator seed can be set with Random.SetSeed
.
Example Usage
for n = 1, 5 do
local d20 = Core.Random.GetInteger(1, 20)
DCEI.LogMessage(d20)
end
-- based on the default seed, the first five rolls will always be:
-- 5, 20, 14, 1, 4
GetNumber
function Random.GetNumber(min: number, max: number)
-> number
Returns a seed-based random float. The random number generator seed can be set with Random.SetSeed
.
Example Usage
local random_number = Core.Random.GetNumber(1, 100)
DCEI.LogMessage(random_number)
-- based on the default seed, this will always be 27.037
SetSeed
function Random.SetSeed(seed: number)
Sets the seed for the random number generator. Use a static number (such as "wave number" or "level number") to generate the same random sequence (such as enemy spawn formation within a wave). Use a dynamic number (such as the time stamp given by os.time()
) to generate new random numbers each time.
Example Usage
Core.Random.SetSeed(1357056)
for n = 1, 5 do
local d20 = Core.Random.GetInteger(1, 20)
DCEI.LogMessage(d20)
end
-- using this seed, the first five rolls will always be:
-- 1, 2, 3, 4, 5
RealTimer
Similar to Os
timers, Real
timers are not affected by game speed.
By default, Real timers update every 0.0625 seconds (this can be overridden with Core.Timer.SetGlobalTickRate
).
New
function RealTimer.New(args: any)
-> RealTimer
SimulationCore
With the exception of Core.HideDefaultUi
, Core mostly includes other class scripts, which are documented separately.
HideDefaultUi
function SimulationCore.HideDefaultUi()
Hides the default game-UI, such as wave and gold counter and ship spell menu.
Color
Class script for converting colors between different formats (hex, RGBA 0-255, RGBA 0-1)
Debug
Contains debugging functions to make it easier to debug between presentation and simulation layers.
Effect
Class script for manipulating effects
Event
Class script for sending events to presentation layer
GameSpeed
Class script for manipulating game speed
Input
Class script for controlling user input, e.g. virtual joysticks
Math
Class script for performing math operations
Point
Class script for manipulating game-points, e.g. {x, y}
tables that correspond to positions on the in-game map
Random
Class script for generating random values
String
Class script for manipulating strings
Table
Class script for manipulating lua tables and dictionaries
Timer
Timer class script useful for repeating, single-use, or infinite timers using game time, real time, or OS time.
Can run functions on completion, every tick, or on a given condition. More performant than other methods of creating timers.
Unit
Class script for manipulating units
Util
Class script for miscellaneous helper functions
String
FormatIntegerDigits
function String.FormatIntegerDigits(amount: number, digits: number)
-> string
Returns a number as a string
with the minimum digits
specified.
Example Usage
local display = Core.String.FormatIntegerDigits(3, 2)
-- display = "03"
FormatNumberDecimalPlaces
function String.FormatNumberDecimalPlaces(amount: number, decimals: number, round?: boolean)
-> string
Returns a number as a string
to the specified number of decimal places. Has an optional round
parameter to round the number to the given decimal place.
Example Usage
local display = Core.String.FormatNumberDecimalPlaces(0.989, 4)
-- display = "0.9890"
local round = true
local display = Core.String.FormatNumberDecimalPlaces(0.989, 2, round)
-- display = "0.99"
FormatNumberToRomanNumeral
function String.FormatNumberToRomanNumeral(number: any)
-> string
Returns a string
as the roman numeral representation of a number.
Example Usage
local display = Core.String.FormatNumberToRomanNumeral(114)
-- display = "CXIV"
FormatNumberWithCommas
function String.FormatNumberWithCommas(amount: number)
-> string
Returns a number as a string
formatted with commas.
Example Usage
local amount = 1234567
local display = Core.String.FormatNumberWithCommas(amount)
-- display = "1,234,567"
local label = DCEI.CreateTextFrame(GMUI.ui.Root)
DCEI.SetTextFrameText(label, display)
FormatTimeHours
function String.FormatTimeHours(time_in_seconds: number, decimals?: number)
-> string
Returns a string
formatted as "HH:MM:SS"
. Has an optional decimals
parameter to display milliseconds.
Example Usage
local time_in_seconds = 7384.559
local display = Core.String.FormatTimeHours(time_in_seconds, 2)
-- display = "02:03:04.56"
local label = DCEI.CreateTextFrame(GMUI.ui.Root)
DCEI.SetTextFrameText(label, display)
FormatTimeMinutes
function String.FormatTimeMinutes(time_in_seconds: number, decimals?: number)
-> string
Returns a string
formatted as "MM:SS
. Has an optional decimals
parameter to display milliseconds.
Example Usage
local time_in_seconds = 7384
local display = Core.String.FormatTimeMinutes(time_in_seconds, 2)
-- display = "123:04.00"
local label = DCEI.CreateTextFrame(GMUI.ui.Root)
DCEI.SetTextFrameText(label, display)
Strip
function String.Strip(str: string, chars: string)
-> string
Returns a string
with the specified chars
removed.
Example Usage
local display = Core.String.Strip("strip that string", "aeiou")
-- display = "strp tht strng"
Table
AddToKeyValue
function Table.AddToKeyValue(table_arg: table, key: string, amount: number)
Adds the amount
to the table entry for the given key
. Negative values are accepted. If the key doesn't exist, a new entry will be created with the amount
.
Example Usage
local fruits = {
bananas = 2,
apples = 3
}
Core.Table.AddToKeyValue(fruits, "bananas", 4)
-- fruits.bananas = 6
Clear
function Table.Clear(table_arg: table)
Removes all keys from the given table. This is useful for resetting table values while preserving table references.
Example Usage
local bar = {}
local baz = {}
for i = 1, 3 do
table.insert(baz, i)
table.insert(bar, i)
end
local foo = {
bar = bar,
baz = baz
}
DCEI.LogMessage(#foo.bar .. ", " .. #foo.baz)
-- logs: "3, 3"
bar = {}
Core.Table.Clear(baz)
for i = 1, 4 do
table.insert(baz, i)
table.insert(bar, i)
end
DCEI.LogMessage(#foo.bar .. ", " .. #foo.baz)
-- logs: "3, 4"
-- by re-initializing `bar` as a new table, we broke the reference between `bar` and `foo.bar`
-- meanwhile Table.Clear() allows us to delete a table's keys without breaking such references
Combine
function Table.Combine(table1: table, table2: table)
-> table|nil
Returns a new table
as a combined list of the values of each input table. Note that this should be used with lists and not dictionaries.
Example Usage
local abc = { "a", "b", "c" }
local def = { "d", "e", "f" }
local abcdef = Core.Table.Combine(foo, bar)
-- abcdef = { "a", "b", "c", "d", "e", "f" }
Contains
function Table.Contains(table_arg: table, value: any)
-> boolean
Returns true
if the table contains the given value.
Example Usage
local equipment = { "sword", "shield", "helmet" }
local has_shield = Core.Table.Contains(equipment, "shield")
-- returns true
CopyAndShuffle
function Table.CopyAndShuffle(table_arg: table)
-> table
Returns a new table
with the shuffled values of the input table. Note that this should be used with lists and not dictionaries.
Example Usage
local deck = { "clubs", "diamonds", "hearts", "spades" }
local shuffled_deck = Core.Table.CopyAndShuffle(deck)
-- shuffled_deck = { "hearts", "spades", "diamonds", "clubs" }
DeepCopy
function Table.DeepCopy(table_arg: table)
-> table
Returns a new table
as a copy of the input table, using copies of any nested tables from the original.
Example Usage
local original = {
foo = { 1, 2, 3 }
}
local deep_copy = Core.Table.DeepCopy(original)
table.insert(deep_copy.foo, 4)
DCEI.LogMessage(#original.foo .. ", " .. #deep_copy.foo)
-- logs: "3, 4"
GetAllKeys
function Table.GetAllKeys(table_to_gather: table)
-> table
Returns a table
as a list of keys from the input table.
Example Usage
local event_table = {
event01 = "WaveStart",
event02 = "WaveWin",
event03 = "WaveLoss",
event04 = "WaveRewards"
}
local keys = Core.Table.GetAllKeys(event_table)
-- keys = { "event01", "event02", "event03", "event04" }
-- note that the collapsed list may not be in the order of the original key-pair values
GetAllValues
function Table.GetAllValues(table_to_gather: table)
-> table
Returns a table
as a list of values from the input table.
Example Usage
local event_table = {
event01 = "WaveStart",
event02 = "WaveWin",
event03 = "WaveLoss",
event04 = "WaveRewards"
}
local values = Core.Table.GetAllValues(event_table)
-- keys = { "WaveStart", "WaveWin", "WaveLoss", "WaveRewards" }
-- note that the collapsed list may not be in the order of the original key-pair values
GetRandomIndex
function Table.GetRandomIndex(roll_table: table)
-> unknown
Returns a random index/key from the given (list/dictionary) table.
Example Usage
local deck = { "clubs", "diamonds", "hearts", "spades" }
local random_deck_index = Core.Table.GetRandomIndex(deck)
-- returns a random value between 1 and 4
GetRandomIndexNoRepeat
function Table.GetRandomIndexNoRepeat(roll_table: any)
-> unknown
Returns a random index/key from the given (list/dictionary) table. Will never return the same index twice in a row for tables with size greater than 1
.
Example Usage
local deck = { "clubs", "diamonds", "hearts", "spades" }
local random_deck_index = Core.Table.GetRandomIndexNoRepeat(deck)
-- returns a random value between 1 and 4
-- subsequent rolls will never repeat the same value twice in row
GetRandomValue
function Table.GetRandomValue(roll_table: any)
-> unknown
Returns a random value from the given table.
Example Usage
local deck = { "clubs", "diamonds", "hearts", "spades" }
local random_card_suit = Core.Table.GetRandomIndex(deck)
-- returns a random card suit
GetRandomValueNoRepeat
function Table.GetRandomValueNoRepeat(roll_table: any)
-> unknown
Returns a random value from the given table. Will never return the same value index twice in a row for tables with size greater than 1
.
Example Usage
local deck = { "clubs", "diamonds", "hearts", "spades" }
local random_card_suit = Core.Table.GetRandomValueNoRepeat(deck)
-- returns a random card suit
-- subsequent rolls will never repeat the same value twice in row
IsEmpty
function Table.IsEmpty(table_arg: table)
-> boolean
Returns true
if the table is empty
Example Usage
local empty_table = {}
local other_table = { false }
local is_empty = Core.Table.IsEmpty(empty_table)
-- returns true
local is_empty = Core.Table.IsEmpty(other_table)
-- returns false
Length
function Table.Length(table_arg: table)
-> integer
Returns the number of values of a table.
Example Usage
local event_table = {
event01 = "WaveStart",
event02 = "WaveWin",
event03 = "WaveLoss",
event04 = "WaveRewards"
}
local length = Core.Table.Length(event_table)
-- length = 4
Merge
function Table.Merge(table1: table, table2: table)
-> table
Returns a new table
of the combined key-pair values of each input table. Any overlapping keys will be overwritten by value of the second input table.
Example Usage
local hero_template = {
strength = 8,
agility = 8,
intellect = 8,
speed = 2,
}
local hero_data = {
name = "Wind Knight",
agility = 12,
abilities = { "Wind Slash" }
}
local wind_knight = Core.Table.Merge(hero_template, hero_data)
-- wind_knight = {
-- name = "Wind Knight",
-- strength = 8,
-- agility = 12,
-- intellect = 8,
-- speed = 2,
-- abilities = { "Wind Slash" }
-- }
ShallowCopy
function Table.ShallowCopy(table_arg: table)
-> table
Returns a new table
as a copy of the input table, using references to any nested tables from the original.
Example Usage
local original = {
foo = { 1, 2, 3 }
}
local shallow_copy = Core.Table.ShallowCopy(original)
table.insert(shallow_copy.foo, 4)
DCEI.LogMessage(#original.foo .. ", " .. #shallow_copy.foo)
-- logs: "4, 4"
Timer
Timers are useful for implementing various time-related gameplay functionality and using many timers is more performant than many DCEI Timer Events.
Creating a new timer by itself won't do anything, but they can be used in conjunction with the common timer methods to accomplish things such as tracking how much time it takes for players to clear a level or to refresh a shop item in 20 minutes.
There are three types of timers, each using the same methods. Each type of timer tracks time differently:
- GameTimers advance using game time with respect to game speed (ex: if game speed is set to 2x, a game timer will advance twice as fast).
- RealTimers advance using "real time" and are not affected by game speed.
- OsTimers advance using os.time() and are also unaffected by game speed. Unlike RealTimers, OsTimers will track the passage of time if the game is running in the background (possible in mobile builds), which makes them more suitable for classic mobile game timer systems.
Timer Update
Game Timers and Real Timers update every 0.0625
seconds. You can change the global time update frequency with Core.Timer.SetGlobalTickRate
is once per second and cannot be changed.
On each timer update, the timer will check its Condition — if true
the timer will run its Action and then Destroy itself, if false
the timer will run its Tick function instead.
By default, a timer's Condition, Action, and Tick functions are all blank, but can be overwritten to provide additional functionality.
if timer:Condition() then
timer:Action()
timer:Destroy()
else
timer:Tick()
end
AddDuration
(method) Timer:AddDuration(duration: number)
Adds time (in seconds) to the timer's duration and sets the timer's Condition
to expire when the timer's time remaining reaches 0. When the timer expires it will run its Action
and then be destroyed.
Example Usage
local timer = Core.Timer.Game.New()
timer:AddDuration(2)
Destroy
(method) Timer:Destroy()
Destroys a timer and stops it from updating.
Example Usage
local timer = Core.Timer.Real.New()
function timer:Tick()
local decimals = 2
local time_elapsed = self:GetTimeElapsed()
local formatted_time = Core.String.FormatTimeMinutes(time_elapsed, decimals)
DCEI.LogMessage("Time Elapsed: " .. formatted_time)
end
DCEI.TriggerAddTimerEventElapsed(
function()
timer:Destroy()
end,
2, true
)
GetTimeElapsed
(method) Timer:GetTimeElapsed()
-> number
Returns how long the timer has been active (in seconds).
Example Usage
local timer = Core.Timer.Real.New()
function timer:Tick()
local decimals = 2
local time_elapsed = self:GetTimeElapsed()
local formatted_time = Core.String.FormatTimeMinutes(time_elapsed, decimals)
DCEI.LogMessage("Time Elapsed: " .. formatted_time)
end
GetTimeRemaining
(method) Timer:GetTimeRemaining()
-> number
Returns how long until the timer expires (in seconds). If no duration has been sit, this will return nil
.
Example Usage
local timer = Core.Timer.Real.New({ duration = 3 })
function timer:Tick()
local decimals = 2
local time_remaining = self:GetTimeRemaining()
local formatted_time = Core.String.FormatTimeMinutes(time_remaining, decimals)
DCEI.LogMessage("Time Remaining: " .. formatted_time)
end
New
function Timer.New(args?: TimerOptions)
-> Timer
Creates and returns a new timer.
Parameters
- (optional) table
args
arguments for constructing the timer.- (optional) float
duration
sets the duration of the timer using theSetDuration
method. A timer with no duration will tick indefinitely. - (optional) function
action
sets the function that will be called when the timer expires by overwriting theAction
method. - (optional) function
tick
sets the function that will be called when the timer updates by overwriting theTick
method. - (optional) function
condition
sets the function that will be evaluated to determine if the timer has expired when the timer updates by overwriting theCondition
method.
- (optional) float
Example Usage
-- creates a timer that expires in 2 seconds and displays a log message when it expires
local timer_a = Core.Timer.Game.New()
timer_a.name = "Timer A"
timer_a:AddDuration(2)
function timer_a:Action()
DCEI.LogMessage("[" .. self.name .. "] has expired")
end
-- timer_b does the same thing as timer_a, but written in the timer constructor
function OnTimerExpire(self)
DCEI.LogMessage("[" .. self.name .. "] has expired")
end
local timer_b = Core.Timer.Game.New({ duration = 2, action = OnTimerExpire })
timer_b.name = "Timer B"
SetDuration
(method) Timer:SetDuration(duration: number)
Sets the timer's duration (in seconds) and sets the timer's Condition
to expire when the timer's time remaining reaches 0. When the timer expires it will run its Action
and then be destroyed.
Example Usage
local timer = Core.Timer.Game.New()
timer:SetDuration(15)
SetGlobalTickRate
(method) Timer.SetGlobalTickRate(value: number)
Used to set the global tick rate of Game
and Real
timers (default is 0.0625
seconds). The global tick rate must be set before any timers are created to take effect.
It may be useful to lower the global tick rate (in increments of 1/16 seconds) to improve performance, particularly if you're using complex timer conditions.
Example Usage
Core.Timer.SetGlobalTickRate(0.25)
local real_timer = Core.Timer.Real.New()
function real_timer:Tick()
local decimals = 2
local time_elapsed = self:GetTimeElapsed()
local formatted_time = Core.String.FormatTimeMinutes(time_elapsed, decimals)
DCEI.LogMessage("Time Elapsed: " .. formatted_time)
end
SetPaused
(method) Timer:SetPaused(flag: boolean)
Pauses a timer if flag is true
or unpauses a timer if flag is false
. Paused timers don't update or expire.
Example Usage
-- this timer will ultimately expire after 4 seconds, since we pause it for 1 second
local timer = Core.Timer.Real.New({ duration = 3 })
function timer:Tick()
local decimals = 2
local time_elapsed = self:GetTimeElapsed()
local formatted_time = Core.String.FormatTimeMinutes(time_elapsed, decimals)
DCEI.LogMessage("Time Elapsed: " .. formatted_time)
end
DCEI.TriggerAddTimerEventElapsed(
function()
timer:SetPaused(true)
end,
2, true
)
DCEI.TriggerAddTimerEventElapsed(
function()
timer:SetPaused(false)
end,
3, true
)
Action
function
The function that will be called when the timer expires
Condition
function
The function that will be evaluated to determine if the timer has expired when the timer updates
Tick
function
The function that will be called when the timer updates
duration
number
Duration of timer
paused
boolean
Bool for the timer pause state
TimerOptions
action
function
Sets the function that will be called when the timer expires by overwriting the Action
method.
condition
function
Sets the function that will be evaluated to determine if the timer has expired when the timer updates by overwriting the Condition
method.
duration
number
Sets the duration of the timer using the SetDuration
method. A timer with no duration will tick indefinitely.
tick
function
Sets the function that will be called when the timer updates by overwriting the Tick
method.
Unit
Damage
function Unit.Damage(unit: any, amount: any)
Deals damage to a unit (without a caster).
Example Usage
Core.Unit.Damage(unit, 5)
GetFacingAngle
function Unit.GetFacingAngle(unit: any)
-> number
Returns the facing angle of the unit. The result will be between -180
and 180
as follows:
90
|
180____|____ 0
-180 |
|
-90
Example Usage
local pos = DCEI.GetUnitPosition2D(unit)
local facing = Core.Unit.GetFacingAngle(unit)
local distance = 4
local forward_point = Core.Point.GetPointWithPolarOffset( pos.x, pos.y, facing, angle)
-- teleports a unit forward a distance of 4
DCEI.SetUnitPosition2D(unit, forward_point.x, forward_point.y)
GetUnitFacingAngle
GetId
function Unit.GetId(unit: Unit)
-> string
Returns a unique unit id as a string
, which is useful for data binding. The returned id will never change and never be associated with another unit.
Example Usage
local unit_type = DCEI.Unit("Standard MeleeUnit")
local unit = DCEI.CreateUnit(1, 1, unit_type, 16, 16)
-- returns an id such as "u4x1xxx4"
local id = Core.Unit.GetId(unit)
DCEI.BindUnitData(id, unit)
HoldPosition
function Unit.HoldPosition(unit: Unit)
Makes a unit with a movement order stop moving. Does not affect the targeting or firing of weapons and abilities.
Example Usage
Core.Unit.HoldPosition(unit)
SendActorMessage
function Unit.SendActorMessage(unit: any, action: string|"broadcastCustomEvent"|"create"|"destroy"|"pauseAnimation"...(+12), ...unknown)
Sends an actor message to the specified unit. This function a variable number of arguments depending on the parameter of the actor message.
Note that the parameters are listed in order.
See actor actions for details of each actor action.
Example Usage
-- tints the unit bright red and plays its attack animation over 2 seconds
Core.Unit.SendActorMessage(unit, "setTintColor", {255, 0, 0})
Core.Unit.SendActorMessage(unit, "playAnimationWithDuration", "attack", 2)
action:
| "create" -- terms: actor, host_site
| "destroy"
| "sendCustomEvent" -- terms: identifier
| "broadcastCustomEvent" -- terms: identifier
| "setModelScale" -- terms: modelScale, duration
| "setVisibility" -- terms: visibility
| "playAnimation" -- terms: clipId
| "playAnimationWithDuration" -- terms: clipId, clipDuration
| "stopAnimation" -- terms: clipId
| "pauseAnimation" -- terms: clipId
| "resumeAnimation" -- terms: clipId
| "setShadow" -- terms: shadowDisplay
| "setModel" -- terms: type, name
| "setTintColor" -- terms: color {r, g, b}
| "setTeamColor" -- terms: color {r, g, b, a}, secondColor {r, g, b, a}
| "setScaleMultiplier" -- terms: scale {x, y, z}
SetBehaviorCount
function Unit.SetBehaviorCount(unit: Unit, behavior: string, count: number)
Sets the stack count of a behavior on the unit
.
Example Usage
local behavior = DCEI.Behavior("Damage Taken None")
Core.Unit.SetBehaviorCount(unit, behavior, 1)
SetFacingAngle
function Unit.SetFacingAngle(unit: Unit, angle: number, duration: number)
Sets a unit's rotation to the specified angle
(in degrees) over the duration
. A duration
of 0 will turn the unit instantly.
Example Usage
-- makes the unit instantly turn 90 degrees clockwise
local facing = Core.Unit.GetFacingAngle(unit)
facing = facing - 90
Core.Unit.SetFacingAngle(unit, facing, 0)
SetFacingPoint
function Unit.SetFacingPoint(unit: Unit, x: number, y: number, duration: number)
Sets a unit's rotation towards the specified point over the duration
. A duration
of 0 will turn the unit instantly.
Example Usage
local pos = DCEI.GetUnitPosition2D(other_unit)
-- makes the unit face the other_unit over 0.5 seconds
Core.Unit.SetFacingPoint(unit, pos.x, pos.y, 0.5)
Util
AddToProtectedValue
function Util.AddToProtectedValue(key: string, amount: number)
Adds the amount
to the protected value for the given key
. Negative values are accepted. If the key doesn't exist, a new protected value will be created with the amount
(though you will get a log error for attempting to read a non-existent key). Note that it is good practice to initialize protected value keys on map start.
Example Usage
local protected_keys = { gems = "gems", gold = "gold" }
for _, key in pairs(protected_keys) do
DCEI.SetProtectedValue(key, 0)
end
Core.Util.AddToProtectedValue(protected_keys.gems, 10)
local gems = DCEI.GetProtectedValue(protected_keys.gems)
-- gems = 10
Assert
function Util.Assert(condition: any, ...string)
If condition
resolves to false/nil; sends an error log with provided message.
Dump
function Util.Dump(o: table)
-> string|unknown
Returns a string
printout of an unpacked table (including all nested tables). Note that nil
values won't be included. Useful for quickly debugging tables.
Example Usage
local mixed_table = {
count = 42,
yee = "haw",
subtable = {
negative = false,
nix = nil,
func = function() return 0 end
}
}
local print = Core.Util.Dump(mixed_table)
DCEI.LogMessage(print)
-- logs: { ["count"] = 42,["subtable"] = { ["func"] = function: 0000018EF9B4AB70,["negative"] = false,} ,["yee"] = haw,}
DumpSimple
function Util.DumpSimple(o: table)
-> string
Returns string
printout of an unpacked table without unpacking nested tables. Note that nil
values won't be included. Useful for quickly debugging tables.
Example Usage
local mixed_table = {
count = 42,
yee = "haw",
subtable = {
negative = false,
nix = nil,
func = function() return 0 end
}
}
local print = Core.Util.DumpSimple(mixed_table)
DCEI.LogMessage(print)
-- logs: { ["count"] = 42,["subtable"] = table: 0000018EFC6C4190,["yee"] = haw,}
ForceToInteger
function Util.ForceToInteger(number: number, func_name?: string)
-> number
Casts a float to an integer by flooring the value. If func_name
is used, a warning will be logged if a float is used here
LogDump
function Util.LogDump(o: table)
Logs the result of Util.Dump
with DCEI.LogMessage()
.
Example Usage
local array = { 4, 8, 15, 16, 23, 42 }
Core.Util.LogDump(array)
-- logs: { [1] = 4,[2] = 8,[3] = 15,[4] = 16,[5] = 23,[6] = 42,}
LogDumpSimple
function Util.LogDumpSimple(o: table)
Logs the result of Util.LogDumpSimple
with DCEI.LogMessage()
.
Example Usage
local array = { 4, 8, 15, 16, 23, 42, poorly_formatted_nested_table = { 1, 2, 3} }
Core.Util.LogDumpSimple(array)
-- logs: { [1] = 4,[2] = 8,[3] = 15,[4] = 16,[5] = 23,[6] = 42,["poorly_formatted_nested_table"] = table: 0000018EFCA12490,}
actor_message
actor_message:
| "create" -- terms: actor, host_site
| "destroy"
| "sendCustomEvent" -- terms: identifier
| "broadcastCustomEvent" -- terms: identifier
| "setModelScale" -- terms: modelScale, duration
| "setVisibility" -- terms: visibility
| "playAnimation" -- terms: clipId
| "playAnimationWithDuration" -- terms: clipId, clipDuration
| "stopAnimation" -- terms: clipId
| "pauseAnimation" -- terms: clipId
| "resumeAnimation" -- terms: clipId
| "setShadow" -- terms: shadowDisplay
| "setModel" -- terms: type, name
| "setTintColor" -- terms: color {r, g, b}
| "setTeamColor" -- terms: color {r, g, b, a}, secondColor {r, g, b, a}
| "setScaleMultiplier" -- terms: scale {x, y, z}