Does Lua support enums?

I want to have an enumeration of a number of states which I can use to control a game loop. The states are mutually exclusive so this is something I would typically use an enum for in other languages.

Are enums supported in Lua?

If so, what’s the syntax?
[import]uid: 8353 topic_id: 2319 reply_id: 302319[/import]

Lua does not support enums.

You could create a table and assign values for them.

t = { apple="green", orange="orange", banana="yellow" }  
for k,v in pairs(t) do print(k,v) end  

Prints the following:

apple green
orange orange
banana yellow

conversely,

local apple = “green”
local orange = “orange”
local banana = “yellow”

Carlos
[import]uid: 24 topic_id: 2319 reply_id: 7142[/import]

No enums as such, but for states I do something like this:

local idle, running, jumping, hiding, shooting = 0, 1, 2, 4, 8  

Of course if they’re exclusive you can just use consecutive numbers. [import]uid: 3953 topic_id: 2319 reply_id: 7156[/import]

Mark,

Could you plz elaborate more on this? Is there any meaning behind those exact numbers? Can you give a code example?

Thanks [import]uid: 7356 topic_id: 2319 reply_id: 7254[/import]

The numbers are just powers of 2 so you can do bitwise comparisons. Problem is that standard Lua library doesn’t inherit C’s bitwise operations (&, | etc) so my suggestion was pretty useless unless your states are mutually exclusive. In that case the numbers can be totally arbitrary. Probably a table solution like Carlos suggested is the Lua way to do it. Also it’s more readable when debugging. [import]uid: 3953 topic_id: 2319 reply_id: 7267[/import]

Hello!
It is such an old post, but for those readers, who are interested in this topic:

You can do enum in such way
[lua]
local fruits = {
apple = {},
orange = {},
pear = {}
}
[/lua]

It works when you don’t care what the actual values are. If you need C-like enums with bitwise operations, I think there is no way to do it easy.

Hello!
It is such an old post, but for those readers, who are interested in this topic:

You can do enum in such way
[lua]
local fruits = {
apple = {},
orange = {},
pear = {}
}
[/lua]

It works when you don’t care what the actual values are. If you need C-like enums with bitwise operations, I think there is no way to do it easy.