Item or Variable Name with Variable as part of the name

Hi @all,
maybe not a big deal, but actually I didn´t find any solution for following task:

There are some Items named with:
Item_1 Item_2 Item_3 ....
How can I access these Items within a rule using a counting variable as part of the item name:
for(var i=1; i<4; i++) postUpdate(Item_(Variable i), something)

Is there also a solution to access variables, using i as part of the name?
Thanks in advance.

AFAIK it is not possible to use items that way nor is it possible to use arrays.
You can use a Group instead!
Put all items in a Group an iterate over all members of that Group.


gItems.allMembers.forEach [item | item.postUpdate(something)]

The following postings might be useful to you:

So the “proper” way to do what you want is to use a Group as illustrated by opus.

If you want to use a variable to construct a name, which has its uses, you have a couple of choices depending on what you want to do. If you only need to postUpdate or sendCommand you can do something like:

for(var i=1; i<4; i=i+1)
    postUpdate("Item_"+i, something.toString)

Note: I’m not 100% positive ++ works in the Rules DSL so I used i+1. Also, the postUpdate/sendCommand Actions require the new state to be passed as a String so if something isn’t already a String you need to call toString. Generally, if you are constructing a for loop like this, you should be using a Group anyway so this example is a bit contrived but should be illustrative.

The second one is useful if you need to get at the Item’s state, historical data, etc. In this case, you need a handle on the Item’s object which you can pull from a Group the Item is a member of. If we have a Group called gGroup which all your Items are members of then:

val myItem = gGroup.members.filter[i|"Item_"+someVar].head
if(myItem.state == OFF) ...
1 Like