Generators, why?

There are some very good reasons why you might want to consider implementing one or more Squirrel generator functions in your code. To learn more about these structures, and to find out how to do put them into action, check out Squirrel Generator Functions, just posted over in the Dev Center.

Thanks for this!

I used this reference and also this thread;

thread disussing infinite loops and generators

to change some old code that I had written for reading frames of data coming from serial. The old code was baaaad, largely because I didn’t have enough experience to set it up nicely. I ported this to use generators today and it went smoother than I expected. I reference the python example that Peter listed in the thread linked above.

//-------------------------UART CODE-------------------------{

//This is our UART function - it is implemented using a generator

const _header = 33; // !
const _footer = 10; // end of line character

imp_uart <- hardware.uart57;

function uart_generator(){

local _result = "";
local returncode = null;
local mybyte=0;

while (true){
    returncode = null;
mybyte =;
    if (mybyte == _header){     //until the header character is seen
        yield null;//leave the loop here - it will resume when a new char comes in
        while (true){
            mybyte =;
            if (mybyte == _footer){
               //put the result out and reset, jump out of this while loop
                returncode =_result;// sent to the calling function, show progress
                _result = "";
            else { // reading the frame
               if (mybyte < 128){ // (my application only uses these characters)
                    _result += format("%c",mybyte); ; //build up the string
                   server.log("byte not valid");
                yield null;
            }//end else
        }//end while
    yield returncode;//loop until you find the header


local _uartReader = uart_generator();

function call_uartReader (){

A machine (number 1 of 9 )sends an update of its cycle count by sending
this string over the shared UART
this example is machine number 1 at a count of 10,913 reps

local uart_result = 0;

uart_result = resume _uartReader;  //Calls the Generator to read the UART

if (uart_result){ //everything but null seems to be true
	local myoutput = split(uart_result,"#");
	if (2 == myoutput.len()){


imp_uart.configure(2400, 8, PARITY_NONE, 1, NO_CTSRTS,call_uartReader);


trust me, it is way better than the old code