Home > Software engineering >  Reset Tcl_NewObj in a loop
Reset Tcl_NewObj in a loop

Time:11-08

My goal is to do a list but in C, with the help of Tcl API.
Tcl loop :

set listObj {}
for {set i 0} {$i < 10} {incr i} {
    set data {}
    lappend data int $i
    lappend listObj $data
}
# result : {{int 0} {int 1} {int 2} {int 3} {int 4} {int 5} {int 6} {int 7} {int 8} {int 9}}

C loop :

Tcl_Obj *listObj = Tcl_NewListObj (0,NULL);
for (int i = 0; i < 10; i  ) {
    Tcl_Obj* data = Tcl_NewObj();

    Tcl_ListObjAppendElement(interp, data, Tcl_NewStringObj("int", 3));
    Tcl_ListObjAppendElement(interp, data, Tcl_NewIntObj(i)); 

    Tcl_ListObjAppendElement(interp, listObj, data);
    
}

It works as expected, but I don't know if data in C code if properly used. In Tcl to reset my variable I'm using this {}.
My question : What’s the way to reset a Tcl_Obj properly with the help of Tcl API ?

CodePudding user response:

Your code is fine. The data variable is just a pointer to a Tcl_Obj. When it is initially created using Tcl_NewObj(), that Tcl_Obj has a refCount of 0. By appending it to listObj, Tcl_ListObjAppendElement() will increment the refCount to 1. At that moment, the Tcl_Obj is effectively handed off to the listObj list.

If you want to be pedantic, you can use Tcl_IncrRefCount(data) after creating the new Tcl_Obj, and use Tcl_DecrRefCount(data) to relinquish your claim to it. That would explicitly reset your variable. But since your code does nothing that risks releasing the variable prematurely, you may safely omit those two calls.

  •  Tags:  
  • ctcl
  • Related