🚀 LSL Programming Language

Version 1.0.1 Stable - A simple, powerful scripting language with Python-like syntax, comprehensive error reporting, and built-in libraries.

✨ Features: Modern error handling • Rich library ecosystem • Multi-language support • IDE integration

Introduction

LSL (Light Scripting Language) is a lightweight scripting language designed for simplicity and readability. It supports basic data types, control structures, functions, classes/objects, file operations, and useful built-in functions.

Blocks are delimited explicitly with keywords like end (or elif/else for conditionals), so indentation is optional (though recommended for readability).

Data Types

Variables and Assignment

Variables are created on first assignment (no declaration needed).

x = 10
name = "Alice"
flag = true
data = [1, 2, 3]
config = {host: "localhost", port: 8080}

Control Structures

If / Elif / Else

if x > 0:
    print "positive"
elif x < 0:
    print "negative"
else:
    print "zero"
end

While

while x < 10:
    print x
    x = x + 1
end

Do-While

do:
    print x
    x = x + 1
end
while x < 10

For (numeric)

for i in 1..10:
    print i
end

For-In (iteration)

for item in my_list:
    print item
end

Loop (repeat n times)

loop 5:
    print "hello"
end

Functions

function greet(name):
    print "Hello, " + name
    return "done"
end

call greet("Bob")  # standalone call
result = call greet("Alice")  # call for return value
print result

Functions can have parameters and return values (or null if no return).

Classes and Objects

LSL supports object-oriented programming with classes, methods, and instance variables.

Basic Class Definition

class Person:
    function __init__(name, age):
        self.name = name
        self.age = age
    end

    function greet():
        print "Hi, I'm " + self.name + " and I'm " + self.age + " years old"
    end
    
    function have_birthday():
        self.age = self.age + 1
        print "Happy birthday! Now I'm " + self.age
    end
end

# Create instances
p1 = new Person("Alice", 30)
p2 = new Person("Bob", 25)

# Call methods
p1.greet()      # Hi, I'm Alice and I'm 30 years old
p2.greet()      # Hi, I'm Bob and I'm 25 years old

# Access properties directly
print p1.name        # Alice
print p2.age         # 25

# Modify properties
p1.have_birthday()  # Happy birthday! Now I'm 31
print p1.age            # 31

Methods with Parameters

class Calculator:
    function __init__():
        self.result = 0
    end
    
    function add(x):
        self.result = self.result + x
        return self.result
    end
    
    function multiply(x):
        self.result = self.result * x
        return self.result
    end
    
    function reset():
        self.result = 0
    end
end

calc = new Calculator()
print calc.add(5)        # 5
print calc.add(3)        # 8
print calc.multiply(2)   # 16
calc.reset()
print calc.result        # 0

Key Concepts

💡 Important: Method calls can be used directly as expressions without 'call' keyword. Use object.method(args) for method calls. Use call function_name(args) for function calls.

Built-in Functions and File Operations

FunctionDescriptionExample
print exprOutputs valueprint "hello"
input "prompt"Read user input with promptname = input "Enter name: "
len(obj)Length of string/list/dictlen("abc")
substring(str, start, len)Substringsubstring("hello", 1, 3)
replace(str, old, new)Replace all occurrencesreplace("aabb", "a", "c")
trim(str)Remove leading/trailing whitespacetrim(" hi ")
split(str, sep)Split stringsplit("a,b,c", ",")
readfile "path"Read entire file as stringcontent = readfile "data.txt"
writefile "path", dataWrite data to filewritefile "out.txt", "hello"
appendfile "path", dataAppend to fileappendfile "log.txt", "event"
createdir "path"Create directorycreatedir "newfolder"
listdir "path"Returns list of entriesfiles = listdir "."
deletedir "path"Delete directorydeletedir "temp"
exists pathFile/directory exists?if exists "file.txt": ...

Input/Output Examples

# Interactive input
name = input "What's your name? "
age = input "How old are you? "

print "Hello, " + name + "!"
print "You are " + age + " years old."

# Simple calculator
print "Simple Calculator"
num1 = input "Enter first number: "
num2 = input "Enter second number: "
result = num(num1) + num(num2)
print "Result: " + result

Modules

use "mymodule.lsl" as my

result = my.my_function(42)

Loads another LSL file and makes its functions available under the given prefix.

📚 Libraries

LSL includes built-in libraries that extend functionality with additional functions. Use them with the use command.

🔢 Math Library

Load with: use math

FunctionDescriptionExample
sin(x)Sine (degrees)sin(90)
cos(x)Cosine (degrees)cos(0)
tan(x)Tangent (degrees)tan(45)
sqrt(x)Square rootsqrt(16)
pow(x, y)Power functionpow(2, 3)
log(x)Natural logarithmlog(10)
exp(x)Exponential functionexp(1)
factorial(x)Factorialfactorial(5)
use math
print sin(90)        # 1
print sqrt(25)       # 5
print pow(2, 4)      # 16
print factorial(6)   # 720

🔤 String Library

Load with: use string

FunctionDescriptionExample
contains(text, substr)Check if text contains substringcontains("hello", "ell")
startswith(text, prefix)Check if text starts with prefixstartswith("hello", "he")
endswith(text, suffix)Check if text ends with suffixendswith("hello", "lo")
to_upper(text)Convert to uppercaseto_upper("hello")
to_lower(text)Convert to lowercaseto_lower("HELLO")
use string
print contains("hello world", "world")  # true
print startswith("hello", "he")          # true
print endswith("hello", "lo")            # true
print to_upper("hello world")            # HELLO WORLD

📋 List Library

Load with: use list

Advanced list manipulation functions (coming soon).

🚀 Advanced Library

Load with: use advanced

Advanced programming functions like map, filter, reduce (coming soon).

🛠️ Error Reporting

LSL provides comprehensive error reporting with precise line numbers and detailed error messages.

Error Types

Error Examples

# Syntax Error examples
print "unclosed string    # [Syntax Error at line 1: Unclosed string literal]
unknown_command          # [Syntax Error at line 2: Unknown command: unknown_command]
bad_function()           # [Syntax Error at line 3: Function calls must use 'call' keyword]

# Runtime Error examples  
use math
print sqrt(-1)           # [Runtime Error at line 6: sqrt() expects a non-negative number]

💡 Pro Tip: All errors include line numbers for quick debugging. The IDE highlights error lines automatically.

Full Example

function factorial(n):
    if n <= 1:
        return 1
    else:
        return n * call factorial(n - 1)  # recursive call
    end
end

result = call factorial(6)  # call for return value
print "Factorial of 6 is: " + result

🎯 Practical Examples

Number Guessing Game

use math

# Number guessing game
secret = call num(call sqrt(random() * 100))  # Random number 1-10
attempts = 0
max_attempts = 5

print "I'm thinking of a number between 1 and 10!"
print "You have " + max_attempts + " attempts."

while attempts < max_attempts:
    guess = input "Enter your guess: "
    guess_num = call num(guess)
    attempts = attempts + 1
    
    if guess_num == secret:
        print "🎉 Congratulations! You got it in " + attempts + " attempts!"
        break
    elif guess_num < secret:
        print "Too low! Try again."
    else:
        print "Too high! Try again."
    end
    
    if attempts == max_attempts:
        print "Game over! The number was " + secret
    end
end

To-Do List Manager

class TodoManager:
    function __init__():
        self.todos = []
    end
    
    function add(task):
        self.todos = self.todos + [task]
        print "Added: " + task
    end
    
    function list():
        if len(self.todos) == 0:
            print "No tasks yet!"
        else:
            print "Your tasks:"
            for i in 1..len(self.todos):
                print i + ". " + self.todos[i-1]
            end
        end
    end
    
    function remove(index):
        if index > 0 and index <= len(self.todos):
            removed = self.todos[index-1]
            # Remove item by creating new list without it
            new_todos = []
            for i in 1..len(self.todos):
                if i != index:
                    new_todos = new_todos + [self.todos[i-1]]
                end
            end
            self.todos = new_todos
            print "Removed: " + removed
        else:
            print "Invalid task number!"
        end
    end
end

# Usage
todo = new TodoManager()
todo.add("Learn LSL programming")
todo.add("Build a project")
todo.list()
todo.remove(1)
todo.list()

File Processor

class FileProcessor:
    function __init__(filename):
        self.filename = filename
        self.content = ""
    end
    
    function read():
        if exists self.filename:
            self.content = readfile self.filename
            print "Read " + len(self.content) + " characters from " + self.filename
            return true
        else:
            print "File not found: " + self.filename
            return false
        end
    end
    
    function count_words():
        words = call split(self.content, " ")
        return len(words)
    end
    
    function count_lines():
        lines = call split(self.content, "\n")
        return len(lines)
    end
    
    function word_frequency():
        words = call split(self.content, " ")
        freq = {}
        for word in words:
            word = call to_lower(call trim(word))
            if word != "":
                if freq[word]:
                    freq[word] = freq[word] + 1
                else:
                    freq[word] = 1
                end
            end
        end
        return freq
    end
end

# Usage
processor = new FileProcessor("sample.txt")
if processor.read():
    print "Words: " + processor.count_words()
    print "Lines: " + processor.count_lines()
    freq = processor.word_frequency()
    print "Unique words: " + len(freq)
end

This guide covers the current AST-based implementation. The language is still evolving.