Button arrays
5 August 2008, 14:29 by Chad Reynoldson
I see a lot of netlinx code that implement integer arrays with button assignments that are looked up using GET_LAST() to provide an index of the button. At first glance, this seems like a good thing to do.
Bad implementation
DEFINE_VARIABLE
CONSTANT INTEGER nBtns[] = {
1001, // Play
1002, // Stop
1003 // Pause
}
DEFINE_EVENT
BUTTON_EVENT[dvTP1a,nBtns]
{
PUSH :
{
STACK_VAR INTEGER nBtnIdx
nBtnIdx = GET_LAST(nBtns)
SWITCH(nBtnIdx)
{
CASE 1 : // Play
CASE 2 : // Stop
CASE 3 : // Pause
{
}
}
}
}
In reality, this is a nightmare to support. First of all, you cannot easily find the code that executes for the button press. Next, you have to search for the button number’s array name (search #1), then search for that block of code (search #2), then scan the case statements hoping you know the exact index (search #3). This is extremely error-prone and just plain unforgiving.
If you would have just stacked the button events in the first place, bam you find the code with the first search, and you would more easily identify it within the block.
Did you know that this is exactly what the compiler will do for you in the first instance of this example using nBtns. The compiler will unroll it anyway, so make your code easier to read and do it first.
Better implementation
DEFINE_EVENT
BUTTON_EVENT[dvTP1a,1001] // Play
BUTTON_EVENT[dvTP1a,1002] // Stop
BUTTON_EVENT[dvTP1a,1003] // Pause
{
PUSH :
{
SWITCH(BUTTON.INPUT.CHANNEL)
{
CASE 1001 : // Play
CASE 1002 : // Stop
CASE 1003 : // Pause
{
}
}
}
}
Comments
Comments are turned off for this article.
