User Tools

Site Tools


enumerations

This is an old revision of the document!


Enumerations

An enumeration (or enum) is a data type containing a set of constant values.

See the list of all available enumerations.


Previously, you could only refer to enum elements as strings. For example, to define the building type of a building, you used BuildingType = “GENERAL”.

Now, all enum values are stored in their enum type's table. This allows for a more clear syntax: BuildingType = BUILDING_TYPE.GENERAL.

The conversion to string is still available with the function toString. You can also convert the enum value to an integer and vice versa with the functions toNumber and fromNumber. These functions are available in the enum table, and directly on the enum tables and enum values.

enum.lua
local stringValue = BUILDING_TYPE.MONUMENT:toString()
-- same as enum.toString(BUILDING_TYPE.MONUMENT)
print(stringValue) -- prints "MONUMENT"
 
local intValue = BUILDING_TYPE.DECORATION:toNumber()
-- same as enum.toNumber(BUILDING_TYPE.DECORATION)
print(intValue) -- prints "2"
 
local enumValue = BUILDING_TYPE:fromNumber(intValue)
-- same as enum.fromNumber(BUILDING_TYPE, intValue)
print (enumValue == BUILDING_TYPE.DECORATION) -- prints ("true")

These functions are useful, for example, to use enum values for bitwise operations. When you want to use the raycast method, the flag argument is used as a bit field containing the different object flags you want your ray cast to collide with. This means you have to create your flag using bitwise operations. To do this, you can use the BitOp module, the functions of which are available in the bit table.

raycast.lua
local raycastResult = {}
 
-- C equivalent: (1 << OBJECT_FLAG.TERRAIN) | (1 << OBJECT_FLAG.WATER) | (1 << OBJECT_FLAG.PLATFORM)
local flag = bit.bor(
	bit.lshift(1, OBJECT_FLAG.TERRAIN),
	bit.lshift(1, OBJECT_FLAG.WATER),
	bit.lshift(1, OBJECT_FLAG.PLATFORM)
)
 
-- Raycast from the screen position [400; 300], forward
-- for a distance of 1000, only on objects with a TERRAIN,
-- WATER or PLATFORM flag
level:rayCast({ 400, 300 }, 1000, raycastResult, flag)
enumerations.1583767763.txt.gz · Last modified: 2020/03/09 11:29 by maxime

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki