Search code examples
integrationqore

How can I get a list from state and modify it in qore?


I am using the ServiceApi::saveStateData({"my-key": some_list}); method to save a list to my qorus IE state. What I wanted to ask is how can I get the list from the state and add/remove elements from the list and put it back in the state? Also I want to know how can I join lists? Like for example I want to join two lists under some_list and put it under state?

Thanks a bunch for the help in advance, Cristi


Solution

  • Lists are always passed by reference, and even though there is a "pseudo-class" for lists (as with other basic types in Qore), all the methods are read-only.

    To make changes to a list, use the +=, +, push, splice, extract operator, unshift, and pop operators.

    Q: How can I add/remove elements from the list?

    Option 1: Use the extract operator to remove elements:

    prompt$: qore -ne 'list<auto> l = (1, 2, 3, 4); printf("removed: %y\n", (extract l, 1, 2)); printf("l: %y\n", l);'
    removed: [2, 3]
    l: [1, 4]
    

    Option 2: Use the remove operator with a range to remove a slice of a list:

    prompt$ qore -ne 'list<auto> l = (1, 2, 3, 4); printf("removed: %y\n", remove l[1..2]); printf("l: %y\n", l);'
    removed: [2, 3]
    l: [1, 4]
    

    Q: How can I join lists?

    Use the +=, + to concatenate lists:

    prompt$ qore -ne 'list<auto> l1 = (1, 2); list<auto> l2 = (3, 4); printf("new list: %y\n", l1 + l2);'
    new list: [1, 2, 3, 4]
    prompt$  qore -ne 'list<auto> l1 = (1, 2); list<auto> l2 = (3, 4); l1 += l2; printf("new list: %y\n", l1);'
    new list: [1, 2, 3, 4]
    

    Note that to add a list as a single element to another list, it's best to use the push operator:

    qore -ne 'list<auto> l1 += (1, 2); list<auto> l2 = (3, 4); push l1, l2; printf("new list: %y\n", l1);'
    new list: [1, 2, [3, 4]]
    

    Note that I used += for the original assignment above to ensure that l1 has type list<auto> - as a simple assignment would have resulted in list<int> which would cause the push expression to throw an exception.

    Also note that as lists are basic types in Qore, they are always passed by value (technically they are passed by reference using copy-on-write semantics), and the "pseudo-class" for lists (as with all pseudo-classes in Qore) implements only read-only methods; updating lvalues in Qore is only done with operators. This is because updating lvalues in Qore is complex due to Qore's multithreaded nature. All Qore operators are thread-atomic, and lvalues can only be changed with operators that guarantee consistency and atomicity even in complex expressions.

    The exception to the above is in objects, which are always passed by reference (actually technically with a copy of a reference, similar to Java); all other value types are passed by value.