测试TCL中是否存在矩阵对象

问题描述 投票:1回答:2

我想测试是否存在tcl-matrix对象。我怎样才能做到这一点?

以下代码无效。

package require struct::matrix

# Test (now we expect 0)
info exists m
# Create the object
struct::matrix m

# Test again, now I expect 1, however it returns 0!!!
info exists m
tcl exists
2个回答
1
投票

使用info commands测试矩阵对象的存在。 info exists测试变量的(非)存在。

% package req struct::matrix
2.0.3
% info commands m
% struct::matrix m
::m
% info commands m
m

背景

矩阵对象实现为Tcl命令(准确地说是别名命令)加上每矩阵Tcl命名空间(作为存储)。

或者,但这在很大程度上取决于当前的实现,您可以测试是否存在这样命名的命名空间:

% package req struct::matrix
2.0.3
% namespace exists m
0
% struct::matrix m
::m
% namespace exists m
1

例如,当矩阵对象重新实现为TclOO对象时,对命令的测试也将继续有效。


0
投票

通过the struct::matrix source code点了一下:

% package req struct::matrix
2.0.3
% set m [struct::matrix]
::matrix1
% expr {$m in [interp aliases]}
1
% string first MatrixProc [interp alias {} $m]
18
% proc is_matrix {name} {
    expr {
         $name in [interp aliases] &&
         [string first MatrixProc [interp alias {} $name]] != -1
    }
}
% is_matrix $m
1

如果你使用struct::matrix m形式,而不是$m,使用完全合格的::m

% struct::matrix m
::m
% is_matrix m
0
% is_matrix ::m
1
© www.soinside.com 2019 - 2024. All rights reserved.