When start scripting with Lua one may notice that its functional range is some what reduced to a tiny set of essential basics. One thing I was missing at least is an enum type. But we could implement something very close.
Before we start I want to recommend the online demo at lua.org. Just paste your lua code into the lua-shell window and press “run” to see if it works.
A very simple enum function could be something like this:
-- Function enum function enum (list) assert ("table" == type(list), "list have to be a table value."); local result = {} for i=1, #list do local name = list[i] assert ("string" == type(name), "enums have to be string values."); result[name] = i result[i] = name end return result; end
With such a function you could use it quite similar to how you would use enums. Here is an example of an enum “InputDeviceType” that has three different enums: “Keyboard”, “Joystick” and “Mouse”. To get the value of the enum you simply use the initial storage “InputDeviceType” and use the enum storage as index.
Here is the example code:
-- typedef some enums: local InputDeviceType = enum { "Keyboard", "Joystick", "Mouse" } -- create a local value storing the enum number. local myDevice = InputDeviceType.Keyboard; -- here is an example of how you could get the enum name agin. print( "Number:", myDevice, " Name:", InputDeviceType[myDevice] ); -- output -- Number:1 Name: Keyboard
There is one drawback to this enum implementation, though. All enums have to be table type (array).