如何知道TCL中变量的数据类型? [英] How to know the Data Type of a variable in Tcl?

查看:7
本文介绍了如何知道TCL中变量的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道TCL中一些变量的数据类型。例如,有三个变量:

set a 10
set b { I love Tcl }
set c "Hello"

假设我对他们的类型一无所知。但我需要知道这一点,才能进一步推进我的工作。那么,我如何才能确定-在上面的示例中-

  • a为整数
  • b是一个列表
  • c是字符串

推荐答案

Tcl的变量根本没有数据类型。所有这些值都可以包含任何值。

TCL的值有类型,但类型系统在很大程度上对脚本隐藏,人们说一切都是字符串是很正常的(因为字符串是TCL中所有其他值类型的超类型)。您的代码也不应该依赖于值的类型,只要您拥有的值可以被强制为正确的类型,这是由TCL的各种操作(例如,强制为列表类型的列表操作、强制为数值类型的算术操作)自动完成的。最新的此类强制被缓存在值中;这使大多数操作实际上相当快。

您可以使用tcl::unsupported::representation命令查看当前TCL系统对某个值类型的看法,这是一个仅限调试的操作。请注意,类型可能并不总是您所期望的类型;系统对您具有不同的键入概念。

set a 10
set b { I love Tcl }
set c "Hello"

# Print the representations; these are all of LITERALS
puts [tcl::unsupported::representation $a]
puts [tcl::unsupported::representation $b]
puts [tcl::unsupported::representation $c]

# Now actually use the values in ways that do type forcing...
set a [expr {$a << 0}]
set b [lrange $b 0 end]
set c [string range [append c u1234] 0 end-1]

# Print the representations again
puts [tcl::unsupported::representation $a]
puts [tcl::unsupported::representation $b]
puts [tcl::unsupported::representation $c]

示例输出(来自我的计算机):

value is a pure string with a refcount of 4, object pointer at 0x7fad2df273d0, string representation "10"
value is a pure string with a refcount of 4, object pointer at 0x7fad2df26e30, string representation " I love Tcl "
value is a pure string with a refcount of 4, object pointer at 0x7fad2df29860, string representation "Hello"
value is a int with a refcount of 2, object pointer at 0x7fad2df2a3a0, internal representation 0xa:0x7fad2df29a40, no string representation
value is a list with a refcount of 2, object pointer at 0x7fad2df27790, internal representation 0x7fad30826510:0x0, no string representation
value is a string with a refcount of 2, object pointer at 0x7fad2df29440, internal representation 0x7fad30826210:0x0, no string representation

最后一行特别奇怪,但这是因为我们已经从UTF-8转换为(大约)UTF-16。

同样,不要使您的代码依赖于类型tcl::unsupported命名空间中命令的行为和格式如有更改,恕不另行通知。值的表示形式可能会在没有事先声明的情况下发生变化(并且不是TclAPI的部分)。如果您正在编写使用表示的C代码,则应将其编写为:

  1. 它是否已经是我的已知代表?
  2. 如果不支持,我是否可以将字符串形式转换为我支持的表示形式?

这篇关于如何知道TCL中变量的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆