Digital Deity

Second Life® and Real Life from Shadowen Silvera

Archive for the ‘Intermediate’ Category

LSL Scripting: Word Wrap / String Format Function

leave a comment »

Feel free to use this however you want. It inserts “returns” ie \n’s at wrap location and takes into account spaces or lack thereof.

string format(string s, integer wrap)
{
    integer len = llStringLength(s); //the length of the string
    integer i = 0; //iterator for our loops
    string tmp;     //used for a substring checking for spaces
    integer j;      //iterator for our nested loop

    //if the length is greater than the wrap size then we need to insert \n's
    //otherwise we will just return the string unmodified
    if(len > wrap) 
    {
        //in the interest of making this function faster we are going to check
        //to see if the string has no spaces at all.. if it does we will simply
        //insert \n's at the wrap setting and then return.
        if(llSubStringIndex(s," ") == -1) //check for spaces
        {
            i = 0; //set our interator at 0.
            do //this loop will insert the \n's
            {
                s = llInsertString(s,i*wrap,"\n"); //insert \n at i * wrap
                i++; //increase the interator
            }while(i<=(len / wrap)); //stop looping when i is greater than len / wrap
            return s; //return the string and exit
        }
        //if we have made it to this point there are spaces in the string
        i = 0; //set our interator at 0.
        do //this loop, like the one above, loops as many times as len / wrap
        {
            j = i * wrap; //j is the index of where to start wrapping from
            //this loop moves backwards from j till it finds a space it then
            //inserts a \n and starts the loop again from the next index.
            do
            {
                tmp = llGetSubString(s,j,j); //grab teh substring at j
                if(tmp == " ") //is it a space?
                {
                    s = llInsertString(s,j,"\n"); //its a space, insert \n
                    jump div; //jump out of this loop and back to main loop
                }
                j--; //space not found yet decrease j by 1 and try again
            }while(j>((i - 1) * wrap)); //keep looping till we have reached the start
           
        s = llInsertString(s,i*wrap,"\n"); //no spaces found, insert \n at wrap point
        //label used for jumping out of nested loop.
        @div;
        i++; //increase i by 1
        }while(i<=(len / wrap)); //loop till reach len / wrap
    }
    //llWhisper(0,"done");
    return s; //return the string
}

Written by tim

October 24, 2008 at 1:14 am

Follow

Get every new post delivered to your Inbox.