-
I created a function that will print enum's name local enumType = #[concept(function(attr)
return attr.type.is_enum
end)]#
-- local Boom = @enum{ A = 0 }
global function printEnum(value: enumType): string
##[[
local type = value.type.symbol
local node = aster.Switch{aster.Id{"value"}}
local arr = {}
for _, field in ipairs(type.value.fields) do
table.insert(arr, {aster.DotIndex{field.name, aster.Id{type.name}}})
table.insert(arr, aster.Block{aster.Return{aster.String{field.name}}})
end
table.insert(node, arr)
table.insert(node, aster.Block{aster.Return{aster.String{"Unknown"}}})
inject_astnode(node)
]]
end
-- it doesn't work here
local Boom = @enum{ A = 0 }
print(printEnum(Boom.A))
but when I use it, the compiler say |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Ok, that's the workaround, is it correct? local enumType = #[concept(function(attr)
return attr.type.is_enum
end)]#
global function printEnum(value: enumType): string
## local type = value.type.symbol
local TargetType = #[value.type]#
##[[
local node = aster.Switch{aster.Id{"value"}}
local arr = {}
for _, field in ipairs(type.value.fields) do
table.insert(arr, {aster.DotIndex{field.name, aster.Id{"TargetType"}}})
table.insert(arr, aster.Block{aster.Return{aster.String{field.name}}})
end
table.insert(node, arr)
table.insert(node, aster.Block{aster.Return{aster.String{"Unknown"}}})
inject_astnode(node)
]]
end
|
Beta Was this translation helpful? Give feedback.
-
The problem with your first example is that the symbol is not visible due to declaration order, your workaround is correct, saving the Congrats on being able to make some interesting function with meta programming! Another possible implementation of this is the following: local enumType = #[concept(function(attr)
return attr.type.is_enum
end)]#
global function printEnum(value: enumType): string
## for i,field in ipairs(value.type.fields) do
if value == #[field.value]# then
return #[field.name]#
end
## end
return 'Unknown'
end
-- it doesn't work here
local Boom = @enum{ A = 0 }
print(printEnum(Boom.A)) This doesn't use the |
Beta Was this translation helpful? Give feedback.
The problem with your first example is that the symbol is not visible due to declaration order, your workaround is correct, saving the
value.type
to the localTargetType
makes the symbol always visible insideprintEnum
.Congrats on being able to make some interesting function with meta programming!
Another possible implementation of this is the following: