Tcl API如何从Tcl获取列表

时间:2012-05-31 10:57:55

标签: c++ tcl

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)?

3 个答案:

答案 0 :(得分:6)

这是一个两阶段的事情。您首先使用Tcl_GetVar系列函数获取值,然后获取您感兴趣的列表部分(通常使用Tcl_SplitListTcl_ListObjGetElements。)< / p>

作为一个更具体的例子:

////// 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...
}

答案 1 :(得分:1)

我不确定,但Tcl_ListObjGetElements看起来像你想要的。或者,Tcl_ObjGetVar2会返回Tcl_Obj,然后您可以使用其余的Tcl API来处理列表对象。

答案 2 :(得分:-1)

您好我发现这个有用的链接包含处理列表的示例:

参考:: 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;
}