User Tools

Site Tools


en:content_creation:lsl_scripting:advanced_lsl

Advanced LSL

resident scripter

Advanced LSL scripting techniques for OpenSimulator.

Introduction

This guide covers advanced LSL (Linden Scripting Language) concepts and techniques for creating sophisticated interactive objects in Caprica. Build on your basic LSL knowledge to create more complex and powerful scripts.

Prerequisites: * LSL Basics — Should be completed first * Understanding of basic programming concepts * Experience with simple LSL scripts

What You'll Learn: * Advanced event handling * State machines * Data structures * Communication between scripts - Optimization techniques - Security considerations

Advanced Events

Event Priority and Flow

Event Execution Order: Events fire in a specific order. Understanding this helps you manage complex interactions.

Common Event Sequence: ``` state_entry → touch_start → touch → touch_end state_exit → [new state] → state_entry ```

Event Collisions: * Multiple events can fire simultaneously - Events queue if processing is slow - Priority determines execution order - Some events can interrupt others

Sensor Events

llSensor: Detect objects or avatars within a radius.

```lsl sensor(integer total_number) {

  integer i;
  for (i = 0; i < total_number; i++)
  {
      key detected_key = llDetectedKey(i);
      string detected_name = llDetectedName(i);
      vector detected_pos = llDetectedPos(i);
      llSay(0, "Detected: " + detected_name);
  }

} ```

llSensorRepeat: Continuous sensor detection.

```lsl default {

  state_entry()
  {
      llSensorRepeat("", NULL_KEY, AGENT, 10.0, PI, 1.0);
  }
  sensor(integer total_number)
  {
      // Handle detection
  }
  no_sensor()
  {
      // Handle no detection
  }

} ```

Collision Events

collision_start: Fires when object collides with something.

```lsl collision_start(integer num_detected) {

  key collider = llDetectedKey(0);
  llSay(0, "Collision with: " + llKey2Name(collider));

} ```

collision_end: Fires when collision ends.

```lsl collision_end(integer num_detected) {

  // Collision ended

} ```

State Machines

Concept

State machines organize script behavior into distinct states, each with its own event handlers. This makes complex scripts more manageable.

Basic State Machine

```lsl integer state_flag = FALSE;

default {

  state_entry()
  {
      llSay(0, "In default state");
  }
  touch_start(integer total_number)
  {
      state active;
  }

}

state active {

  state_entry()
  {
      llSay(0, "In active state");
      state_flag = TRUE;
  }
  touch_start(integer total_number)
  {
      state default;
  }
  state_exit()
  {
      state_flag = FALSE;
  }

} ```

State Machine with Timer

```lsl integer step = 0;

default {

  state_entry()
  {
      state processing;
  }

}

state processing {

  state_entry()
  {
      step = 0;
      llSetTimerEvent(1.0);
  }
  timer()
  {
      if (step < 5)
      {
          llSay(0, "Step: " + (string)step);
          step++;
      }
      else
      {
          llSetTimerEvent(0.0);
          state default;
      }
  }

} ```

Data Structures

Lists

Lists are LSL's primary data structure for storing multiple values.

Creating Lists: ```lsl list my_list = [“apple”, “banana”, “cherry”]; list numbers = [1, 2, 3, 4, 5]; list mixed = [“text”, 42, <1,2,3>, “more text”]; ```

List Operations: ```lsl Get length integer length = llGetListLength(my_list); Get element string first = llList2String(my_list, 0);

Add element my_list = llListInsertList(my_list, [“date”], 3); Remove element my_list = llDeleteSubList(my_list, 0, 0);

Find element integer index = llListFindList(my_list, [“banana”]); ``` List Iteration: ```lsl list items = [“a”, “b”, “c”, “d”]; integer i; integer count = llGetListLength(items); for (i = 0; i < count; i++) { string item = llList2String(items, i); llSay(0, item); } ``` ==== Strided Lists === Strided lists organize data in fixed-width groups. ```lsl list inventory = [“sword”, 10, “shield”, 5, “potion”, 20]; Extract name string item_name = llList2String(inventory, i * 2);

Extract quantity integer quantity = llList2Integer(inventory, i * 2 + 1); ``` ===== Inter-Script Communication ===== ==== Link Messages === Send messages between scripts in the same linkset. Sending: ```lsl llMessageLinked(LINK_SET, 0, “Hello from script”, NULL_KEY); ``` Receiving: ```lsl link_message(integer sender_num, integer num, string str, key id) { llSay(0, “Received: ” + str); } ``` Link Message Channels: * Different numbers for different message types - Use constants for clarity - Negative numbers for private messages ==== HTTP Requests === Make HTTP requests to external services. ```lsl key request_id; default { touch_start(integer total_number) { request_id = llHTTPRequest(“http://example.com/api”, [HTTP_METHOD, “GET”], “”); } http_response(key request_id, integer status, list metadata, string body) { if (request_id == request_id) { llSay(0, “Response: ” + body); } } } ``` ==== Region-Side to Client-Side Communication === llDialog: Show dialog to user. ```lsl list buttons = [“Option 1”, “Option 2”, “Option 3”]; default { touch_start(integer total_number) { llDialog(llDetectedKey(0), “Choose an option:”, buttons, -1); } listen(integer channel, string name, key id, string message) { llSay(0, “Selected: ” + message); llListenRemove(channel); } } ``` ===== Advanced Techniques ===== ==== Memory Management === LSL Memory Limits: * Scripts have limited memory (usually 64KB) - Monitor memory usage - Optimize memory-intensive operations - Use memory-efficient data structures Memory Monitoring: ```lsl integer free_memory = llGetFreeMemory(); llOwnerSay(“Free memory: ” + (string)free_memory + “ bytes”); ``` Memory Optimization: * Use lists efficiently - Avoid string concatenation in loops - Clear variables when done - Use llGetFreeMemory() to monitor ==== Timer Management === Multiple Timers: LSL only supports one timer per state. Use workarounds: ```lsl float timer_interval = 1.0; integer timer_step = 0; default { state_entry() { llSetTimerEvent(timer_interval); } timer() { timer_step++; if (timer_step % 2 == 0) { Do task every 2 seconds

      }
      if (timer_step % 10 == 0)
      {
          // Do task every 10 seconds
      }
  }

} ```

Rotation Mathematics

Quaternions: LSL uses quaternions for rotation.

```lsl Create rotation rotation rot = llEuler2Rot(<0, 0, 90 * DEG_TO_RAD>); Apply rotation llSetRot(rot);

Combine rotations rotation combined = rot1 * rot2; Get Euler angles vector euler = llRot2Euler(rot); ```

Rotation between points: ```lsl vector start = <10, 10, 10>; vector end = <20, 20, 20>; vector direction = llVecNorm(end - start); rotation look_at = llRotBetween(<0, 0, 1>, direction); ```

Security Considerations

Input Validation

Validate User Input: ```lsl listen(integer channel, string name, key id, string message) {

  // Validate input
  if (llStringLength(message) > 50)
  {
      llSay(0, "Input too long");
      return;
  }
  // Process valid input

} ```

Permission Security

Check Permissions: ```lsl if (llGetPermissions() & PERMISSION_TRIGGER_ANIMATION) {

  // Has permission

} else {

  // Request permission
  llRequestPermissions(llGetOwner(), PERMISSION_TRIGGER_ANIMATION);

} ```

Anti-Griefing

Protect Your Scripts: * Validate llDetectedKey() - Check llDetectedOwner() - Use llSameGroup() - Limit sensitive operations

Optimization Techniques

Script Efficiency

Avoid Busy Loops: ```lsl BAD while (TRUE) { Do something

  llSleep(0.1);

}

GOOD default { state_entry() { llSetTimerEvent(0.1); } timer() { Do something

  }

} ```

Use llGetListEntryType: ```lsl integer type = llGetListEntryType(my_list, index); 0 = invalid, 1 = integer, 2 = float, 3 = string, 4 = key, 5 = vector, 6 = rotation ``` ==== Listener Management === Clean Up Listeners: ```lsl integer listen_handle; default { state_entry() { listen_handle = llListen(0, “”, NULL_KEY, “”); } state_exit() { llListenRemove(listen_handle); } } ``` ===== Debugging ===== ==== Debugging Techniques === llOwnerSay: Send messages only to owner. ```lsl llOwnerSay(“Debug: variable = ” + (string)variable); ``` llSetText: Display debug info above object. ```lsl llSetText(“Status: ” + status, <1,1,1>, 1.0); ``` Debug Channel: Use a specific channel for debug messages. ```lsl integer DEBUG_CHANNEL = -123456; llSay(DEBUG_CHANNEL, “Debug message”); ``` ===== Best Practices ===== ==== Code Organization === * Use meaningful variable names - Comment complex logic - Break into functions - Use constants for magic numbers ==== Error Handling === * Check return values - Handle errors gracefully - Provide user feedback - Log errors ==== Performance === * Minimize listener usage - Optimize loops - Use state machines - Clean up resources ===== Resources ===== ==== LSL Reference === * LSL Portal: https://wiki.secondlife.com/wiki/LSL_Portal - LSL Wiki: https://wiki.secondlife.com/wiki/LSL_Wiki - OpenSimulator LSL Documentation ==== Community === * LSL Scripting forums - OpenSimulator scripting groups - Caprica scripting community ===== Next Steps ===== Now that you understand advanced LSL: * Practice with complex scripts - Experiment with state machines - Optimize your code - Share your scripts - Learn from others Advanced LSL scripting opens up many possibilities. Keep learning and experimenting!

en/content_creation/lsl_scripting/advanced_lsl.txt · Last modified: 2026/10/04 19:11 (external edit)

Page Tools