Search code examples
linden-scripting-language

How can I read a random line from a notecard in LSL?


I have a notecard with a different word on each line, and I'd like to be able to select from the lines randomly. How can I do that?


Solution

  • First, as you mention, you need a notecard. For this example, I'm using one named "colors" with the following contents:

    red
    blue
    green
    yellow
    orange
    purple
    

    With that notecard present, the following script will read and chat a random line from the card each time the prim is touched.

    //this script will grab and chat a random line from the "colors" notecard each time the prim is touched.
    
    string card = "colors";
    key linecountid;
    key lineid;
    integer linemax;
    
    integer random_integer( integer min, integer max )
    {
      return min + (integer)( llFrand( max - min + 1 ) );
    }
    
    
    default
    {
        state_entry()
        {
            //get the number of notecard lines
            linecountid = llGetNumberOfNotecardLines(card);
        }
    
        touch_start(integer total_number)
        {
            lineid = llGetNotecardLine(card, random_integer(0, linemax));
        }
    
        dataserver(key id, string data)
        {
            if (id == linecountid)
            {
                linemax = (integer)data - 1;
            }
            else if (id == lineid)
            {
                llSay(0, data);
            }
        }
    }