Itcl configbody 的适当 return 值

Itcl Appropriate return value of configbody

我想从 configbody 中 return 但不能在不导致变量未被设置的情况下明确地这样做。

我想帮助理解我所看到的行为。请考虑以下代码(使用 Itcl 3.4):

package require Itcl
catch {itcl::delete class Model}
itcl::class Model {
    public variable filename "orig"
}

itcl::configbody Model::filename {
    if 1 {
        return ""
    } else {
    }
}

Model my_model
my_model configure -filename "newbie"
puts "I expect the result to be 'newbie:' [my_model cget -filename]"

当我return空字符串时,文件名没有设置为新值。如果我不 return 而只是让 proc 失败,文件名就会改变。您可以通过将上面代码中的 1 更改为 0 来看到这一点。

我怀疑它与以下内容有关statement:

When there is no return in a script, its value is the value of the last command evaluated in the script.

如果有人能解释这种行为以及我应该如何 returning,我将不胜感激。

Tcl 通过抛出异常(TCL_RETURN 类型)来处理 return。通常,过程或方法处理程序的外部部分会拦截该异常并将其转换为 procedure/method 的正常结果,但您可以使用 catch 拦截内容并深入了解。

但是,configbody 不使用该机制。它只是在某些上下文中运行脚本(不确定是什么!)并且该上下文将 TCL_RETURN 视为更新失败的指示。

解决方法:

itcl::configbody Model::filename {
    catch {
        if 1 {
            return ""
        } else {
        }
    } msg; set msg
    # Yes, that's the single argument form of [set], which READS the variable...
}

或者在 configbody 中调用真正的方法,传入任何需要的信息。