Title: Windows Live Agents: SCount Function (Safe Count)
Slug: windows-live-agents-scount-function-safe-count
Date: 2008-02-09 15:57:00
Author: Kartones
Lang: en
Tags: Development, Windows Live Agents
Description: Creating a 'safe count' function in Buddyscript to handle looping scalars and lists, addressing limitations of the Count function.

 <p align="justify">Buddyscript has objects, but internally they are n-dimensional arrays of strings. They can have properties, like real objects, but have some limitations.</p> <p align="justify">One I've come across recently was that the Buddyscript "<font face="Courier New">for each</font>" can't iterate a non-list object (a scalar), and because of code restrictions, we had to be able to handle both looping scalars and lists. Of course this can be done with a simple "<font face="Courier New">if</font>" that uses the <font face="Courier New">Count()</font> function and behaves differently if we have one or N elements.</p> <p align="justify">But the Count function is a bit fragile. If the variable passed is not a list it will throw an exception. So I've made a small "safe count" function to allow counting scalars (as 1), lists and empty scalars (as 0):</p> <p><font face="Courier New">function SCount(LIST)<br>  if (!Exist(LIST))<br>    return 0<br>  if (LIST == "")<br>    return 0<br>  if (IsObject(LIST))<br>    return Count(LIST)<br>  else<br>    return 1</font> </p><p align="justify"> </p> <p align="justify">This is a small test-pattern I made to test it:</p> <p><font face="Courier New">+ _test_scount<br>    VAR1 = ""<br>    VAR2 = ""<br>    VAR2.EL = ""<br>    VAR3 = ""<br>    VAR3.EL = 1<br>    VAR4 = ""<br>    VAR4[0] = 1<br>    VAR5 = ""<br>    VAR5.EL = ""<br>    VAR5.EL[0] = 1<br>    VAR6 = ""<br>    VAR6.EL = ""<br>    VAR6.EL[0] = 1<br>    VAR6.EL[1] = 2<br>    VAR6.EL[2] = 3    <br>    RES = SCount(VAR1)<br>    - var1: RES<br>    nop<br>    RES = SCount(VAR2.EL)<br>    - var2.el: RES<br>    nop<br>    RES = SCount(VAR3.EL)<br>    - var3.el: RES<br>    nop<br>    RES = SCount(VAR4)<br>    - var4[0]: RES<br>    nop<br>    RES = SCount(VAR5.EL)<br>    - var5.el: RES<br>    nop<br>    RES = SCount(VAR6.EL)<br>    - var6.el: RES</font> </p><p align="justify"> </p> <p align="justify">And this are the output results:</p> <p><i><font face="Courier New">var1: 0<br>var2.el: 0<br>var3.el: 1<br>var4[0]: 1<br>var5.el: 1<br>var6.el: 3</font></i></p>
