#71 Lua enum values in tables

open
nobody
None
5
2012-12-21
2010-04-28
Zack S.
No

One of the beautiful bits of using SWIG to get Lua bindings to my C++ code is that it magically provides me with the ability to use introspection and reflection on my C++ types. I can, for instance, recurse through a class and print all of its fields.

However, in the case of enumerations, all of the values are placed in the interpreter's global table with nothing distinguishing them from each other. I would love it if enums like the following:

enum Fruits { APPLE = 0, ORANGE, BANANA, GRAPE };
enum Vegetables { CARROT, BROCCOLI, LETTUCE, CELERY };

would become Lua tables named "Fruits" and "Vegetables" in the bindings produced. That way I could iterate over "Fruits" and "Vegetables" to find out what values of each type my software currently supports. At present, these enums will be provided in my module as:

mod_name.APPLE
mod_name.ORANGE
mod_name.BANANA
mod_name.GRAPE
mod_name.CARROT
mod_name.BROCCOLI
mod_name.LETTUCE
mod_name.CELERY

with nothing to distinguish one type from another. I believe that the rest of the implementation regarding enums could stay the same in terms of error checking et al. Heck, even if there was just an optional flag to produce these tables in addition to the global variables that would be terrific.

Thanks for your time! Keep up the great work, SWIG team! : D

Discussion