Looping trough all elements of an enum with a for loop

Hello,
I’m new to vala and gtk, and I am trying to loop trough all the items of an enum, so I wrote for (ConfigToken t=0;t<ConfigToken.T_AMOUNT;t++) but I’m getting error: unsupported lvalue in postfix expression.
The weird thing is that, when I write for (ConfigToken t=0;t<ConfigToken.T_AMOUNT;t=t+1) I’m getting no warning and no error.
Is it really the right way to do it, or is there a better way?
Thanks

First thing to say is: Don’t do that.
Enums are not a traversable collection, they’re used in a unique different way. Learn about it.

Anyway, I lack the technical knowledge to explain it effectively… All I can say is that a few months ago I gave an an answer on stackoverflow an among 15 answers suggesting to use a magic number, my solution (which has some considerations before even thinking about using it) got an anonymous negative feedback. So I should stay away from this kind of questions.

Considering you’re explicitly saying you’re new to something, I will underline the first paragraph of this answer as the thing to do while you don’t get a technical answer. Nevertheless, if that thing is all you really need to do, the link to the SO answer there could give you some inspiration. But again, think twice if you’re making an incorrect use of a data type

First the compiler error is very probably a bug, as it works with a workaround, and it would be good if you file a bug in Issues · GNOME / vala · GitLab.

Your way to achieve this is one option, but I wouldn’t add an enum entry just to get the length of it (T_AMOUNT). A better solution would be to add a constant with the amount of entries inside the enum that you then can use further.

1 Like

If it helps you there is also Adw.EnumListModel, which gives you a listmodel with all enum entries. You can then loop through that.

1 Like

I wrote an issue Incrementing the value of an enum is not working (#1460) · Issues · GNOME / vala · GitLab.

Thanks for your answers

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.