专栏
标签
使用 Meta.parse() 转换字符串以便 eval 时:ERROR: UndefVarError: `this` not defined
技术分享
发布于 2025-07-10 10:36:32
查看 1过去327天

Meta 无法识别 local 环境的变量,因此需要将 this 改为 this_,定义一个全局变量 this_,将函数入参 this 赋值给 this_,就可以识别到字符串表达式中的变量。
示例:

1.运行下面代码,可以看到出现了报错:

@kwdef mutable struct GLB
    f1::Float64 = pi
    n1::Int64 = 3
end
@kwdef mutable struct HTOP
    glb::GLB = GLB()
end
eval_str = "id1 = this.glb.f1 * this.glb.n1 + 1"

function tt(this::HTOP, eval_str)
    eval(Meta.parse(eval_str))
    @show id1
end

tt(HTOP(), eval_str)

image.png
2.修改代码如下:

@kwdef mutable struct GLB
    f1::Float64 = pi
    n1::Int64 = 3
end
@kwdef mutable struct HTOP
    glb::GLB = GLB()
end
# eval_str = "id1 = this.glb.f1 * this.glb.n1 + 1"  
eval_str = "id1 = this_.glb.f1 * this_.glb.n1 + 1"  #this 改为 this_

function tt(this::HTOP, eval_str)
    global this_, id1   #定义全局变量 this_ 和 id1
    this_ = this    #将 this 赋参给 this_
    eval(Meta.parse(eval_str))
    @show id1
    this_ = nothing #重置 this_
end

tt(HTOP(), eval_str)

3.运行上述代码,可以看到运行出正确结果:
image.png

所属专栏:Syslab基础平台
产品信息:Syslab科学计算环境
科学计算

全部回答

暂无数据
暂无数据
用户
和原帖交流更多问题细节吧,去
我要发帖 我要发帖
资料中心 资料中心
查看更多>
热门帖子 热门帖子
主要贡献者 主要贡献者
过去7天