local Enum = require("enum") -- Require the library
-- Create an enum either with variable amount of variables, or a table holding it.
local Directions = Enum("Up", "Down", "Left", "Right")
local Directions = Enum({"Up", "Down", "Left", "Right"})
-- Access a enum simply with the key.
local myDirection = Directions.Up
local myDirection = Directions["Up"]
-- Perform logic with them
if myDirection == Directions.Up then
print("Were moving up, boss!")
elseif myDirection == Directions.Down then
print("Ship is going down!")
end
-- Some nice to knows
local myDirection = Directions.Sideways -- Error: Attempt to index non-existant enum 'Sideways'.
myDirection.foo = "bar" -- Error: "Attempt to write to static enum"
Hey Tjakka, it's a cute idea but I'm not 100% convinced that enums would be useful in a dynamic language like Lua.
Perhaps if you had a more practical example I might reconsider my point.
Other than that, the entire lib can be summarized up as a list to map operation:
function table.map(list)
local map = {}
for i = 1, #list do
local v = list[i]
if map[v] then
error("duplicate value in list:"..tostring(v))
end
map[v] = i
end
return map
end
This snippet might be more useful as it ensures the list doesn't contain duplicates
and it stores the index of each value in the list which might be useful for reverse lookup.
It is indeed a feature that may not be really needed, I posted it mainly because people in the Discord group wanted it.
2 things regarding your snippet versus mine though.
1. My system also ensures there are no duplicates with the nature of how it stores, key = key.
2. In my system you can also print the lookup (myDirections.North), instead of using the key.
Looping over and printing works similar in both. Difference being that my system could use either the key or the value, while you need to use the key, but you would get a consistent order.
Tjikka, you need a stronger example, showcasing the advantages of these "enums".
To be honest, I think using string literals is generally simpler/cleaner: if myDirection == "up" then
It should be noted that string comparison in Lua is quite fast.
Having a generalized way to declare a static list of accepted values and to check user-supplied literals against that list is a good thing, and helps writing better code. With pure string literals you always have to write that annoying else error(...). You don't want that. Don't repeat yourself.