Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tcl API how to get a list from Tcl

Tags:

c++

tcl

Tcl 8.4

In my Tcl script:

set foo1 false
set foo2 "yes"
set foo3 [list item1 item2 item3]

There's a API to get scalars like foo1 or foo2. Eg: Tcl_GetVar(tcl_interp, string("foo1").c_str(), flags). I was wondering if there's any API to get list (like foo3) from Tcl?

like image 447
Stan Avatar asked May 31 '12 10:05

Stan


1 Answers

It's a two-stage thing. You first fetch the value with one of the Tcl_GetVar family of functions, then you get the pieces of the list that you're interested in (with Tcl_SplitList or Tcl_ListObjGetElements, normally).

As a more concrete example:

////// 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...
}
like image 169
Donal Fellows Avatar answered Oct 14 '22 13:10

Donal Fellows