-
I want to list constants string values in enums but enums only support integral values why not values other than integers? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
While making an enum with strings officially is not planned, this doable with meta programming, and here I will share how. 1. Naive enumFirst you can use a simple naive enum of strings using global record fields, like this: -- Define an enum of strings.
global MyStringEnum: type = @record{}
global MyStringEnum.A: string = 'A'
global MyStringEnum.B: string = 'B'
-- Example of use
print(MyStringEnum.A)
print(MyStringEnum.B) Like you can see, we have to declare meta fields in the record for each enum field. 2. Macro string enumThe naive enum works, but can we compress the syntax by generating the enum through the preprocessor? Turns out we can: -- Define macro that will create an enum
## local function make_StringEnumT(map)
global T: type = @record{}
## for k,v in pairs(map) do
global T.#|k|# = #[v]#
## end
## return T
## end
-- Example of use
local MyStringEnum: type = #[make_StringEnumT{
A = 'A',
B = 'B',
}]#
print(MyStringEnum.A)
print(MyStringEnum.B) Using the macro 3. Generic string enumThe macro string enum worked, but we had to invoke the preprocessor to create an enum, could we use a generic to create the enum? So the syntax feels less dense, turns out we can: -- Enum generic
## local function make_StringEnumT(initlist)
global T: type = @record{}
## for _,pair in ipairs(initlist) do
global T.#|pair[1]|# = #[pair[2]]#
## end
## return T
## end
global StringEnum: type = #[generic(make_StringEnumT)]#
-- Example of use
local MyStringEnum: type = @StringEnum{
A = 'A',
B = 'B',
}
print(MyStringEnum.A)
print(MyStringEnum.B) Now if you move Final notesPlease have in mind Nelua is designed this way, some interesting features to have (like this one) are not available officially in the core to make the language specification and its compiler simpler. As this feature is doable with simple meta programming it is not planned, as it would be redundant. |
Beta Was this translation helpful? Give feedback.
While making an enum with strings officially is not planned, this doable with meta programming, and here I will share how.
1. Naive enum
First you can use a simple naive enum of strings using global record fields, like this:
Like you can see, we have to declare meta fields in the record for each enum field.
2. Macro string enum
The naive enum works, but can we compress the syntax by generating the enum through the preprocessor? Turns out we can: