Lua does not have native support for "enums", but they are quite easy to emulate.
Naively, they can be implemented as a table that contains unique values for each key. While strings or numbers suffice, I find that simply using empty tables work best:
local Result = {
Success = {},
Failure = {},
}
Since Lua's comparison operator (==
) for table check if the two sides are the same object, not if they have the same fields, Result.Sucess ~= Result.Failure
. This is more efficient than comparing two strings and saves the developer from the hassle of picking a unique value for each field.
In a unityped languages such as Lua, a record of unique values acts pretty much as an enum in other languages.
If the syntax is too alien for you, this mechanism can be easily automated:
local enum = function(keys)
local Enum = {}
for _, value in ipairs(keys) do
Enum[value] = {}
end
return Enum
end
local Result = enum { "Success", "Failure" }
assert(Result.Success == Result.Success)
assert(Result.Failure == Result.Failure)
assert(Result.Success ~= Result.Failure)