Why does jsvUnLock() not return the JsVar?

Posted on
  • I am wondering if there was a reason that jsvUnLock() does not return the JsVar that it is unlocking?

    If it did, it would seem to offer me a new way of coding. For example, today I have the option of coding:

    JsVar *x = jsvNewFromInteger(10);
    jsvUnLock(x);
    

    while if jsvUnLock() returned its passed in JsVar, then I would appear to have the option:

    JsVar *x = jsvUnLock(jsvNewFromInteger(10));
    
  • Ahh, that's because doing:

    JsVar *x = jsvUnLock(jsvNewFromInteger(10));
    

    Would introduce a bug. When you jsvUnLock, if the amount of locks and references equals 0 then the variable will be freed, so what you're left with will just be an unused variable. (a 'new' variable will have one lock, and no references).

    It's a bit like asking why you can't do:

    void *foo = free(malloc(50));
    

    There are a very few cases where you could do what you suggest, but 90% of the time it'll introduce a bug, which is why it got left off :)

  • This is great info ... it is demonstrating that I don't understand JsVars anywhere near as well as I thought I did.

    What is the algorithm on "UnLock"? Is it a counter? Is it a boolean? If it is a counter, is it considered "freed" if the count reaches zero?

    A discussion on JsVar usage would make a great session for board contributors.

  • Well, there should really be more info in http://www.espruino.com/Internals

    There are 2 counters:

    • locks - incremented when you turn a JsVarRef into a JsVar*. After all the js*Kill functions are called, all of these should be 0, because nothing should 'have' a pointer any more.
    • references - incremented when you 'reference' one variable from another (eg. objects, names, etc).

    When you do trace() you get those values written next to each variable.

    And yes, when both hit 0 the variable is unallocated and added to the 'free list' of variables.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Why does jsvUnLock() not return the JsVar?

Posted by Avatar for Kolban @Kolban

Actions