Negative Indexing

Prev Next

Introduction

Python, a common programming language, supports negative indexing for arrays. B4P applies negative indexing on a broader range. Typically, the -1 refers to the last element, with -2, -3, etc. referring to the elements further up (or leftward). At present, negative indexing is used in the following:

  • Arrays (-1 = last element)
  • Table row numbers (-1 = last row)
  • Table column number (-1 = last column. Few exceptions exists where -1 refers to a vacant column after the last one, and is documented so if it applies)
  • Set elements (-1 = last set element)
  • Function parameters (in selected functions where documented)

Negative numbers must be at least big enough in order to access the first element / row / column. Going further will result in exceptions (error messages).

Programming example
       array( a[], { ha, he, hi, ho, hu } );
       structure( b[], { reptile, mammal, bird, fish }, { turtle, deer, swallow, dorade } );
       c[] = { Hah, Heh, Hih, Hoh, Huh };

       echo( a[-2], "  ", a[-1] ); // ho, hu
       echo( b[-2], "  ", b[-1] ); // deer, turtle (last two acc. to alphabetic order of structure members)
       echo( c[]{-2}, "  ", c[]{-1} ); // Hoh, Huh

       echo(new line, "Example with tables:");
       table initialize( t, { { Last Name, First Name, Street, City, Country },
           { Adams, Abel, Main St, S. Francisco, USA }, { Billson, Bill, South St, London, UK } } );

       echo( [t:-2,-1] ); // Last row, 2nd last column.  It's 'London'.
       echo( [t:-1,-1] ); // Last row, last column.  It's 'UK'.        
Outcome
ho  hu
deer  turtle
Hoh  Huh

Example with tables:
London
UK
Try it yourself: Open LAN_Features_negative_indexing.b4p in B4P_Examples.zip. Decompress before use.