I am starting to try and use/understand meta-programming and wanted to create a macro to overload the
getproperty function for custom types that are custom implementation of the Point in GeometryBasics (subtypes of StaticVectors) , and can have either 2 or 3 dimensions.
I wanted to create a macro
@custom_getproperty that allowed to assign custom property names to this types so that for example I type:
@custom_getproperty MyType (:x,:y), the macro would generate a custom
getproperty implementation that access x and y as the first and second element of the :data field of the custom type (:data is the only field of the type).
To try and have the capability of creating 2 or 3 elseif branches depending on the number of the propertynames provided as a tuple, I ended up creating this macro code.
macro custom_getproperty(name,symbolstuple) a = "function Base.getproperty(obj::$(name),s::Symbol) if s == :data getfield(obj,:data) " for (i,sym) in enumerate(eval(symbolstuple)) a *= "elseif s == $(Meta.quot(sym)) getfield(obj,:data)[$i] " end a *= "else error(\"The $(name) type does not have a \$(String(s)) property\") end end" esc(Meta.parse(a)) end
While this appears to work in achieving the functionality I wanted, I do feel this is somehow a bad/evil way of dealing with this problem.
Is there a better/cleaner way of achieving this functionality in a macro?