Skip to content

Debugging Scripts

When scripts don't work as expected, this guide helps you identify and fix the problem.


Understanding Error Messages

When a script fails, LoomCAD shows an error message with useful information:

Script Error

Error Components

PartDescription
Error typeWhat kind of error occurred
MessageDescription of the problem
Line numberWhere in the script the error occurred
Code contextThe problematic line highlighted

Common Errors

Syntax Errors

Problem: JavaScript syntax is invalid.

javascript
// Missing closing bracket
runScriptCommand('drawComponent', {
  name: 'J101',
  x: 200
// <- Missing }

Fix: Check brackets, quotes, and commas. The error message shows the line number.

Command Not Found

Problem: Unknown command name.

javascript
// Wrong: 'createComponent' doesn't exist
runScriptCommand('createComponent', {...})

// Right: Use 'drawComponent'
runScriptCommand('drawComponent', {...})

Fix: Check the Command Reference for correct command names.

Missing Required Parameters

Problem: A required parameter is missing.

javascript
// Missing 'name' parameter
runScriptCommand("drawComponent", {
  x: 200,
  y: 300,
  pinCount: 8,
});

Error message: "Required parameter 'name' is missing"

Fix: Add the missing parameter.

Element Not Found

Problem: Trying to update or query an element that doesn't exist.

javascript
// Component 'ECU99' doesn't exist
runScriptCommand("updateComponent", {
  query: "ECU99",
  update: { partnumber: "NEW" },
});

Error message: "Component 'ECU99' not found"

Fix: Verify the element name or ID is correct. Use queryComponent to check.

Type Errors

Problem: Wrong data type for a parameter.

javascript
// pinCount should be a number, not a string
runScriptCommand("drawComponent", {
  name: "J1",
  pinCount: "eight", // Wrong!
});

Fix: Use the correct data type:

  • Numbers: 8 not '8'
  • Strings: 'text' with quotes
  • Arrays: [1, 2, 3]
  • Objects: { x: 100, y: 200 }

Debugging Techniques

1. Add Console Logging

Insert scriptConsole.log() to see what's happening:

javascript
const result = runScriptCommand("queryComponent", {});
const components = result.elements.filter(c => c.name.startsWith("J"));
scriptConsole.log("Found components:", components.length);
scriptConsole.table(components); // Show as table

for (const comp of components) {
  scriptConsole.log(`Processing: ${comp.name}`);
  // ... rest of code
}

2. Check Return Values

Commands return data - inspect it:

javascript
const result = runScriptCommand("drawComponent", {
  name: "TEST",
  x: 100,
  y: 100,
  pinCount: 4,
});

scriptConsole.log("Create result:", result);
// Shows: { success: true, ... }

3. Test Incrementally

Don't run the whole script at once. Test piece by piece:

javascript
// Step 1: Just create the component
runScriptCommand('drawComponent', {...})
scriptConsole.log('Step 1 complete')

// Comment out the rest until Step 1 works
/*
runScriptCommand('drawWire', {...})
runScriptCommand('updateComponent', {...})
*/

4. Validate Queries First

Before bulk operations, check what will be affected:

javascript
// First, see what we're working with
const result = runScriptCommand("queryWire", {});
const redWires = result.elements.filter(
  w => w.colors && w.colors.includes("red")
);
scriptConsole.log(`Will update ${redWires.length} wires:`);
scriptConsole.table(
  redWires.map(w => ({ name: w.name, coreSizeAWG: w.coreSizeAWG }))
);

// Only proceed if it looks right
// Uncomment below after verifying:
// for (const wire of redWires) {...}

5. Use Try-Catch

Wrap risky code in error handling:

javascript
// Check if element exists before updating
const result = runScriptCommand("queryComponent", { query: "MAYBE_EXISTS" });
if (result.success && result.elements.length > 0) {
  runScriptCommand("updateComponent", {
    query: "MAYBE_EXISTS",
    update: { partnumber: "NEW" },
  });
  scriptConsole.log("Update successful");
} else {
  scriptConsole.warning("Component not found, skipping update");
}

Validation Errors

LoomCAD validates command parameters before execution. Common validation errors:

Invalid Enum Value

javascript
// 'purple' is not a valid DIN 47100 color
runScriptCommand("drawWire", {
  fromComponent: "ECU1",
  fromPin: 1,
  toComponent: "J101",
  toPin: 1,
  colors: ["purple"], // Invalid!
});

Valid colors: white, brown, green, yellow, grey, pink, blue, red, black, violet, orange

Out of Range

javascript
// pinCount must be positive
runScriptCommand("drawComponent", {
  name: "J1",
  x: 100,
  y: 100,
  pinCount: -5, // Invalid!
});

Invalid Pattern

javascript
// Name can't contain certain characters
await runScriptCommand("drawComponent", {
  name: "J/101", // '/' may not be allowed
});

Understanding the Execution Model

How Scripts Execute

LoomCAD scripts execute synchronously. All commands are queued and processed, with changes applied only after the entire script completes.

javascript
// All commands execute in order
runScriptCommand("drawComponent", { name: "J1", x: 100, y: 100, pinCount: 4 });
runScriptCommand("drawComponent", { name: "J2", x: 200, y: 100, pinCount: 4 });

// Query results reflect the state BEFORE script started
const result = runScriptCommand("queryComponent", {});
// result.elements won't include J1 or J2 yet!

scriptConsole.log("Script finished - components will appear now");
// J1 and J2 appear after this script completes

Querying Newly Created Elements

Problem: Can't query elements created earlier in the same script.

Solution: Either:

  1. Store data you need in variables as you create elements
  2. Run a separate script to query after creation completes
javascript
// Store what you need as you go
const createdComponents = [];

for (let i = 1; i <= 5; i++) {
  const name = `J${i}`;
  runScriptCommand("drawComponent", {
    name: name,
    x: 100 * i,
    y: 100,
    pinCount: 4,
  });
  createdComponents.push(name);
}

// Use your stored data
scriptConsole.log(`Created: ${createdComponents.join(", ")}`);

Recovery from Failed Scripts

Undo Changes

If a script made unwanted changes:

  1. Press Ctrl+Z repeatedly to undo
  2. Or use the undo history menu:

Undo Menu

Partial Execution

If a script failed mid-way:

  • Some changes were made, some weren't
  • Undo all changes, fix the script, run again
  • Or manually fix the remaining items

Corrupted State

If the design seems broken:

  1. Save a backup: Project > Export as JSON
  2. Refresh the browser
  3. If still broken, contact support with the JSON export

Getting Help

Ask the AI

Copy your error message and ask:

"This script is failing with error: [paste error]. What's wrong?"

The AI can often identify the issue and suggest fixes.

Check the Error Line

The error message includes a line number. Look at that specific line:

Error at line 15: Cannot read property 'name' of undefined

Line 15 is trying to access .name on something that's undefined.

Simplify and Isolate

If you can't find the bug:

  1. Make a copy of the script
  2. Remove half the code
  3. Does it work now? Bug is in the removed half.
  4. Repeat until you find the problem line

Script Checklist

Before running a script, verify:

  • All strings are quoted: 'text' not text
  • All brackets match: {...}, [...], (...)
  • Variable names are spelled consistently
  • Required parameters are included
  • Enum values are valid (colors, types, etc.)
  • Element names/IDs being referenced exist
  • Queries use exact names (no wildcards like *)
  • Update commands use { query: '...', update: {...} } format

Next Steps