ahm*_*hm5 5 macros metaprogramming syntax-error julia
function check(str,arg;type=DataType,max=nothing,min=nothing,description="")
@argcheck typeof(arg)==type
@argcheck arg>min
@argcheck arg<max
@argcheck typeof(description)==String
return arg
end
function constr(name,arg,field)
return :(function $name($arg,$field)
new(check($name,$arg,$field))
end)
end
macro creatStruct(name,arg)
code = Base.remove_linenums!(quote
struct $name
end
end)
print(arg)
append!(code.args[1].args[3].args,[constr(name,arg.args[1].args[1],arg.args[1].args[2])])
code
end
macro myStruct(name,arg)
@creatStruct name arg
end
@myStruct test12 (
(arg1,(max=10))
)
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我试图构建一个macro创建 a 的对象struct,并且在结构中,您可以定义带有边界(最大、最小)和描述等的参数。我收到此错误:语法:"#141#max = 10" is not a valid function argument name
每次我尝试解决它时,我都会收到另一个错误,例如:
LoadError: syntax: "struct" expression not at top level
所以,我认为我的代码/方法没有那么有凝聚力。任何人都可以提出建议和/或其他方法。
max您正在尝试使用默认值 来创建参数名称10。错误是关于max=10不是有效名称 ( Symbol),而实际上max是。更大的问题是您试图将其放入struct表达式而不是构造函数方法中:struct Foo
bar::Float64
max::Int64
end
# constructor
Foo(bar, max=10) = Foo(bar, max)
Run Code Online (Sandbox Code Playgroud)
因此,您还必须弄清楚如何为具有默认值的方法创建表达式。
structs 必须在顶层定义。“顶级”类似于全局范围,但在某些情况下更严格;我不知道确切的区别,但它绝对排除本地范围(macro、function等)。看起来问题是通过creatStruct在 中作为代码求值而返回的表达式myStruct,但LoadError我收到的消息有不同的消息。无论如何,如果我确保事情保持为表达式,错误就会消失:macro myStruct(name,arg)
:(@creatStruct $name $arg)
end
Run Code Online (Sandbox Code Playgroud)