Tcl 8.4
在我的 Tcl 脚本中:
set foo1 false
set foo2 "yes"
set foo3 [list item1 item2 item3]
有一个 API 可以获取像 foo1 或 foo2 这样的标量。例如:Tcl_GetVar(tcl_interp, string("foo1").c_str(), flags)
。我想知道是否有任何 API 可以从 Tcl 获取列表(如 foo3)?
这是一个两阶段的事情。您首先使用Tcl_GetVar
函数系列之一获取值,然后获得您感兴趣的列表片段(通常使用Tcl_SplitList
or Tcl_ListObjGetElements
)。
作为一个更具体的例子:
////// FETCH FROM VARIABLE //////
// The NULL is conventional when you're dealing with scalar variable,
// and the 0 could be TCL_GLOBAL_ONLY or
Tcl_Obj *theList = Tcl_GetVar2Ex(interp, string("foo1").c_str(), NULL, TCL_LEAVE_ERR_MSG);
if (theList == NULL) {
// Was an error; message in interpreter result...
}
////// EXTRACT ELEMENTS //////
int objc;
Tcl_Obj **objv;
if (Tcl_ListObjGetElements(interp, theList, &objc, &objv) == TCL_ERROR) {
// Not a list! error message in interpreter result...
}
////// WORK WITH VALUES //////
for (int i=0 ; i<objc ; i++) {
const char *value = Tcl_GetString(objv[i]);
// Whatever...
}
我不确定,但Tcl_ListObjGetElements
看起来像你想要的。或者,Tcl_ObjGetVar2
也可以返回 a Tcl_Obj
,然后您可以使用 Tcl API 的其余部分来操作它以处理列表对象。
嗨,我发现这个有用的链接包含处理列表的示例:
参考::https ://www.tcl.tk/man/tclx8.2/TclCommandWriting.3.html
int Tcl_LreverseObjCmd(notUsed, interp, objc, objv)
ClientData notUsed; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj **obj; /* Argument strings. */
{
int listObjc, lowListIndex, hiListIndex;
Tcl_Obj **listObjv;
char *temp, *resultList;
Tcl_Obj **newListObjv;
/* Verify argument count. Since we take only one argument, argument
* count must be 2 (command plus one argument).
*/
if (objc != 2)
return TclX_WrongArgs (interp, objv [0], "list");
/* Create an object to handle the new list we're creating */
newListObjv = Tcl_NewObj();
/* Crack the list at objv[1] into its own count and array of object
* pointers.
*/
if (Tcl_ListObjGetElements (interp, objv[1], &listObjc, &listObjv) != TCL_OK) {
return TCL_ERROR;
}
/* For each element in the source list from last to first, append an
* element to the new list.
*/
for (listIndex = listObjc - 1; listIndex >= 0; listIndex--) {
Tcl_ListObjAppendElement (interp, newListObjv, listObjv[listIndex]);
}
FIX: NEED TO RETURN THE LIST.
return TCL_OK;
}