cleanup structure
This commit is contained in:
40
examples/01_basic_features.luash
Normal file
40
examples/01_basic_features.luash
Normal file
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env luash
|
||||
-- Basic Luash Demo: Environment Variables and Shell Commands
|
||||
|
||||
print("=== Basic Luash Features ===\n")
|
||||
|
||||
-- Environment variable access (clean syntax)
|
||||
print("1. Environment Variables:")
|
||||
print(" User: " .. $USER)
|
||||
print(" Shell: " .. $SHELL)
|
||||
print(" Home: " .. $HOME)
|
||||
|
||||
-- Environment variable assignment
|
||||
print("\n2. Setting Environment Variables:")
|
||||
$MY_VAR = "Hello from Luash!"
|
||||
print(" Set MY_VAR = " .. $MY_VAR)
|
||||
|
||||
-- String literals preserve $ symbols
|
||||
print("\n3. Strings preserve $ literals:")
|
||||
print(" This prints literally: $USER and $HOME are variables")
|
||||
|
||||
-- Shell command execution with backticks
|
||||
print("\n4. Shell Commands:")
|
||||
hostname = `hostname`
|
||||
print(" Hostname: " .. hostname)
|
||||
|
||||
date_info = `date +"%Y-%m-%d %H:%M:%S"`
|
||||
print(" Current time: " .. date_info)
|
||||
|
||||
-- Interactive commands for direct output
|
||||
print("\n5. Interactive Commands:")
|
||||
print(" Directory listing:")
|
||||
!ls -la
|
||||
|
||||
print("\n6. Combining Lua logic with shell:")
|
||||
files = `ls -1`
|
||||
file_count = 0
|
||||
for line in files:gmatch("[^\n]+") do
|
||||
file_count = file_count + 1
|
||||
end
|
||||
print(" Found " .. file_count .. " files in current directory")
|
||||
75
examples/02_quick_comparison.luash
Normal file
75
examples/02_quick_comparison.luash
Normal file
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env luash
|
||||
-- Quick Examples: Bite-sized demos showing luash vs bash
|
||||
|
||||
print("=== Luash vs Bash: Quick Examples ===\n")
|
||||
|
||||
print("1. Environment Variables")
|
||||
print(" Bash: echo $USER")
|
||||
print(" Luash: print($USER)")
|
||||
print(" → " .. $USER)
|
||||
|
||||
print("\n2. Variable Assignment")
|
||||
print(" Bash: MY_VAR=\"hello\"")
|
||||
print(" Luash: $MY_VAR = \"hello\"")
|
||||
$MY_VAR = "hello"
|
||||
print(" → " .. $MY_VAR)
|
||||
|
||||
print("\n3. Command Substitution")
|
||||
print(" Bash: current_dir=$(pwd)")
|
||||
print(" Luash: current_dir = `pwd`")
|
||||
current_dir = `pwd`
|
||||
print(" → " .. current_dir)
|
||||
|
||||
print("\n4. Conditional Logic")
|
||||
print(" Bash: if [ -f \"README.md\" ]; then echo \"exists\"; fi")
|
||||
print(" Luash: if `test -f README.md` == \"\" then print(\"missing\") else print(\"exists\") end")
|
||||
if `test -f README.md && echo "yes"` == "yes" then
|
||||
print(" → exists")
|
||||
else
|
||||
print(" → missing")
|
||||
end
|
||||
|
||||
print("\n5. Loops with Arrays")
|
||||
print(" Bash: for file in *.lua; do echo $file; done")
|
||||
print(" Luash: files = `ls *.lua`; for file in files:gmatch(\"[^\\n]+\") do print(file) end")
|
||||
files = `ls *.luash`
|
||||
print(" → Files found:")
|
||||
for file in files:gmatch("[^\n]+") do
|
||||
print(" " .. file)
|
||||
end
|
||||
|
||||
print("\n6. String Processing")
|
||||
print(" Bash: echo \"hello world\" | tr '[:lower:]' '[:upper:]'")
|
||||
print(" Luash: string.upper(\"hello world\")")
|
||||
print(" → " .. string.upper("hello world"))
|
||||
|
||||
print("\n7. Math Operations")
|
||||
print(" Bash: result=$((5 + 3))")
|
||||
print(" Luash: result = 5 + 3")
|
||||
result = 5 + 3
|
||||
print(" → " .. result)
|
||||
|
||||
print("\n8. File Operations")
|
||||
print(" Bash: cat file.txt | wc -l")
|
||||
print(" Luash: line_count = `cat luash | wc -l`")
|
||||
line_count = `cat luash | wc -l`
|
||||
print(" → " .. line_count .. " lines in luash script")
|
||||
|
||||
print("\n9. Error Handling")
|
||||
print(" Bash: command || echo \"failed\"")
|
||||
print(" Luash: if `command 2>/dev/null` == \"\" then print(\"failed\") end")
|
||||
if `nonexistent_command 2>/dev/null` == "" then
|
||||
print(" → command failed (as expected)")
|
||||
end
|
||||
|
||||
print("\n10. Complex Data Structures")
|
||||
print(" Bash: (limited array support)")
|
||||
print(" Luash: Full Lua tables!")
|
||||
data = {
|
||||
users = {"alice", "bob", "charlie"},
|
||||
scores = {alice = 95, bob = 87, charlie = 92}
|
||||
}
|
||||
print(" → Users: " .. table.concat(data.users, ", "))
|
||||
print(" → Alice's score: " .. data.scores.alice)
|
||||
|
||||
print("\n✨ Luash combines the best of shell scripting with Lua's power!")
|
||||
31
examples/03_interpolation.luash
Normal file
31
examples/03_interpolation.luash
Normal file
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env luash
|
||||
-- Variable Interpolation Demo
|
||||
|
||||
print("=== Variable Interpolation in Shell Commands ===\n")
|
||||
|
||||
print("1. Basic variable interpolation:")
|
||||
service = "ssh"
|
||||
result = `pgrep #{service} | wc -l`
|
||||
print(" Processes named '" .. service .. "': " .. result)
|
||||
|
||||
print("\n2. Multiple variables in one command:")
|
||||
dir = "/tmp"
|
||||
pattern = "*.log"
|
||||
files = `find #{dir} -name #{pattern} 2>/dev/null | wc -l`
|
||||
print(" Files matching '" .. pattern .. "' in " .. dir .. ": " .. files)
|
||||
|
||||
print("\n3. Network connectivity check:")
|
||||
host = "google.com"
|
||||
ping_result = `ping -c 1 #{host} >/dev/null 2>&1 && echo "ok" || echo "fail"`
|
||||
print(" " .. host .. " is " .. (ping_result == "ok" and "reachable" or "unreachable"))
|
||||
|
||||
print("\n4. Dynamic file operations:")
|
||||
filename = "README.md"
|
||||
if `test -f #{filename}` ~= "" then
|
||||
lines = `wc -l < #{filename}`
|
||||
print(" " .. filename .. " has " .. lines .. " lines")
|
||||
else
|
||||
print(" " .. filename .. " not found")
|
||||
end
|
||||
|
||||
print("\n✨ Use #{variable} syntax to substitute Lua variables into shell commands!")
|
||||
78
examples/04_system_admin.luash
Normal file
78
examples/04_system_admin.luash
Normal file
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env luash
|
||||
-- System Administration Demo: Real-world sysadmin tasks
|
||||
|
||||
print("=== System Administration with Luash ===\n")
|
||||
|
||||
-- System information gathering
|
||||
print("1. System Information:")
|
||||
os_name = `uname -s`
|
||||
architecture = `uname -m`
|
||||
uptime_info = `uptime`
|
||||
|
||||
print(" OS: " .. os_name)
|
||||
print(" Architecture: " .. architecture)
|
||||
print(" Uptime: " .. uptime_info)
|
||||
|
||||
-- Process management
|
||||
print("\n2. Process Management:")
|
||||
process_count = `ps aux | wc -l`
|
||||
print(" Total processes: " .. process_count)
|
||||
|
||||
-- Check if important services are running
|
||||
print("\n3. Service Status Check:")
|
||||
services = {"ssh", "cron", "systemd"}
|
||||
for i = 1, #services do
|
||||
local service = services[i]
|
||||
local result = `pgrep #{service} | wc -l`
|
||||
if tonumber(result) > 0 then
|
||||
print(" ✓ " .. service .. " is running")
|
||||
else
|
||||
print(" ✗ " .. service .. " not found")
|
||||
end
|
||||
end
|
||||
|
||||
-- Disk usage analysis
|
||||
print("\n4. Disk Usage:")
|
||||
disk_usage = `df -h /`
|
||||
print(" Root filesystem:")
|
||||
!df -h / | tail -1
|
||||
|
||||
-- Log file analysis
|
||||
print("\n5. Log Analysis:")
|
||||
if `test -f /var/log/syslog && echo "exists"` == "exists" then
|
||||
print(" Recent system errors:")
|
||||
!tail -5 /var/log/syslog | grep -i error || echo " No recent errors found"
|
||||
else
|
||||
print(" Syslog not accessible (normal on macOS)")
|
||||
end
|
||||
|
||||
-- Network connectivity check
|
||||
print("\n6. Network Check:")
|
||||
hosts_to_check = {"google.com", "github.com"}
|
||||
for i = 1, #hosts_to_check do
|
||||
local host = hosts_to_check[i]
|
||||
local ping_result = `ping -c 1 #{host} >/dev/null 2>&1 && echo "ok" || echo "fail"`
|
||||
if ping_result == "ok" then
|
||||
print(" ✓ " .. host .. " is reachable")
|
||||
else
|
||||
print(" ✗ " .. host .. " is unreachable")
|
||||
end
|
||||
end
|
||||
|
||||
-- Generate a simple system report
|
||||
print("\n7. Generating System Report:")
|
||||
$REPORT_DATE = `date`
|
||||
report = "System Report - " .. $REPORT_DATE .. "\n"
|
||||
report = report .. "User: " .. $USER .. "\n"
|
||||
report = report .. "System: " .. os_name .. " " .. architecture .. "\n"
|
||||
report = report .. "Processes: " .. process_count .. "\n"
|
||||
|
||||
-- Write report to file (using Lua's file operations)
|
||||
local file = io.open("system_report.txt", "w")
|
||||
if file then
|
||||
file:write(report)
|
||||
file:close()
|
||||
print(" Report saved to system_report.txt")
|
||||
else
|
||||
print(" Failed to write report file")
|
||||
end
|
||||
126
examples/05_development.luash
Normal file
126
examples/05_development.luash
Normal file
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env luash
|
||||
-- Development Workflow Demo: Git, building, and deployment tasks
|
||||
|
||||
print("=== Development Workflow with Luash ===\n")
|
||||
|
||||
-- Check if we're in a git repository
|
||||
print("1. Git Repository Check:")
|
||||
git_status = `git status 2>/dev/null || echo "not_a_repo"`
|
||||
if git_status ~= "not_a_repo" then
|
||||
current_branch = `git branch --show-current`
|
||||
print(" ✓ Git repository detected")
|
||||
print(" Current branch: " .. current_branch)
|
||||
|
||||
-- Check for uncommitted changes
|
||||
changes = `git status --porcelain`
|
||||
if changes ~= "" then
|
||||
print(" ⚠ Uncommitted changes detected")
|
||||
else
|
||||
print(" ✓ Working directory clean")
|
||||
end
|
||||
else
|
||||
print(" ✗ Not a git repository")
|
||||
end
|
||||
|
||||
-- Project setup and dependency management
|
||||
print("\n2. Project Dependencies:")
|
||||
project_files = {"package.json", "requirements.txt", "Cargo.toml", "go.mod"}
|
||||
for i = 1, #project_files do
|
||||
local file = project_files[i]
|
||||
local exists = `test -f ` .. file .. ` && echo "yes" || echo "no"`
|
||||
if exists == "yes" then
|
||||
print(" Found " .. file)
|
||||
|
||||
-- Run appropriate install command
|
||||
if file == "package.json" then
|
||||
print(" Installing npm dependencies...")
|
||||
!npm install
|
||||
elseif file == "requirements.txt" then
|
||||
print(" Python project detected")
|
||||
!pip install -r requirements.txt
|
||||
elseif file == "Cargo.toml" then
|
||||
print(" Rust project detected")
|
||||
!cargo build
|
||||
elseif file == "go.mod" then
|
||||
print(" Go project detected")
|
||||
!go mod tidy
|
||||
end
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
-- Build and test automation
|
||||
print("\n3. Build and Test:")
|
||||
$BUILD_START = `date`
|
||||
print(" Build started at: " .. $BUILD_START)
|
||||
|
||||
-- Simple build logic based on project type
|
||||
if `test -f Makefile && echo "yes"` == "yes" then
|
||||
print(" Running make...")
|
||||
build_result = `make 2>&1`
|
||||
if string.find(build_result, "error") or string.find(build_result, "Error") then
|
||||
print(" ✗ Build failed")
|
||||
print(" " .. build_result)
|
||||
else
|
||||
print(" ✓ Build successful")
|
||||
end
|
||||
elseif `test -f package.json && echo "yes"` == "yes" then
|
||||
print(" Running npm build...")
|
||||
!npm run build 2>/dev/null || echo " No build script found"
|
||||
else
|
||||
print(" No build system detected")
|
||||
end
|
||||
|
||||
-- Code quality checks
|
||||
print("\n4. Code Quality:")
|
||||
code_files = `find . -name "*.lua" -o -name "*.js" -o -name "*.py" | head -10`
|
||||
if code_files ~= "" then
|
||||
line_count = `find . -name "*.lua" -o -name "*.js" -o -name "*.py" | xargs wc -l 2>/dev/null | tail -1 | awk '{print $1}'`
|
||||
print(" Total lines of code: " .. line_count)
|
||||
|
||||
file_count = `find . -name "*.lua" -o -name "*.js" -o -name "*.py" | wc -l`
|
||||
print(" Code files: " .. file_count)
|
||||
end
|
||||
|
||||
-- Deployment preparation
|
||||
print("\n5. Deployment Preparation:")
|
||||
$VERSION = `git describe --tags 2>/dev/null || echo "v1.0.0"`
|
||||
print(" Version: " .. $VERSION)
|
||||
|
||||
-- Create deployment package
|
||||
print(" Creating deployment package...")
|
||||
package_name = "deploy_" .. string.gsub($VERSION, "%.", "_") .. ".tar.gz"
|
||||
|
||||
-- Use Lua string manipulation instead of shell interpolation
|
||||
!tar --exclude='.git' --exclude='node_modules' --exclude='*.log' -czf deploy_package.tar.gz .
|
||||
|
||||
if `test -f deploy_package.tar.gz && echo "yes"` == "yes" then
|
||||
package_size = `du -h deploy_package.tar.gz | cut -f1`
|
||||
print(" ✓ Package created: deploy_package.tar.gz (" .. package_size .. ")")
|
||||
else
|
||||
print(" ✗ Package creation failed")
|
||||
end
|
||||
|
||||
-- Environment-specific deployment
|
||||
print("\n6. Environment Deployment:")
|
||||
$DEPLOY_ENV = "staging" -- Could be passed as argument
|
||||
print(" Target environment: " .. $DEPLOY_ENV)
|
||||
|
||||
-- Simulate deployment steps
|
||||
deployment_steps = {
|
||||
"Validating package integrity",
|
||||
"Backing up current version",
|
||||
"Uploading new version",
|
||||
"Running database migrations",
|
||||
"Restarting services",
|
||||
"Running health checks"
|
||||
}
|
||||
|
||||
for i = 1, #deployment_steps do
|
||||
print(" " .. i .. ". " .. deployment_steps[i] .. "...")
|
||||
-- In real deployment, these would be actual commands
|
||||
`sleep 0.5` -- Simulate work
|
||||
print(" ✓ Complete")
|
||||
end
|
||||
|
||||
print("\n 🚀 Deployment to " .. $DEPLOY_ENV .. " completed successfully!")
|
||||
158
examples/06_data_processing.luash
Normal file
158
examples/06_data_processing.luash
Normal file
@@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env luash
|
||||
-- Data Processing Demo: File processing, text manipulation, and analysis
|
||||
|
||||
print("=== Data Processing with Luash ===\n")
|
||||
|
||||
-- Create sample data for demonstration
|
||||
print("1. Creating Sample Data:")
|
||||
sample_data = [[timestamp,user,action,value
|
||||
2024-01-01 10:00:00,alice,login,1
|
||||
2024-01-01 10:05:00,bob,purchase,25.50
|
||||
2024-01-01 10:10:00,alice,logout,1
|
||||
2024-01-01 10:15:00,charlie,login,1
|
||||
2024-01-01 10:20:00,bob,purchase,15.75
|
||||
2024-01-01 10:25:00,charlie,purchase,45.00]]
|
||||
|
||||
-- Write sample data to file
|
||||
local file = io.open("sample_data.csv", "w")
|
||||
file:write(sample_data)
|
||||
file:close()
|
||||
print(" Sample CSV data created: sample_data.csv")
|
||||
|
||||
-- File analysis using shell commands
|
||||
print("\n2. File Analysis:")
|
||||
line_count = `wc -l < sample_data.csv`
|
||||
print(" Total lines: " .. line_count)
|
||||
|
||||
file_size = `du -h sample_data.csv | cut -f1`
|
||||
print(" File size: " .. file_size)
|
||||
|
||||
-- Data extraction and filtering
|
||||
print("\n3. Data Extraction:")
|
||||
print(" Purchase transactions:")
|
||||
!grep "purchase" sample_data.csv
|
||||
|
||||
-- Using Lua for more complex processing
|
||||
print("\n4. Advanced Processing with Lua:")
|
||||
local data_file = io.open("sample_data.csv", "r")
|
||||
local purchases = {}
|
||||
local users = {}
|
||||
|
||||
-- Skip header line
|
||||
data_file:read("*line")
|
||||
|
||||
-- Process each line
|
||||
for line in data_file:lines() do
|
||||
local timestamp, user, action, value = line:match("([^,]+),([^,]+),([^,]+),([^,]+)")
|
||||
|
||||
if action == "purchase" then
|
||||
table.insert(purchases, {
|
||||
timestamp = timestamp,
|
||||
user = user,
|
||||
amount = tonumber(value)
|
||||
})
|
||||
end
|
||||
|
||||
users[user] = true
|
||||
end
|
||||
data_file:close()
|
||||
|
||||
-- Calculate statistics
|
||||
local total_amount = 0
|
||||
local purchase_count = #purchases
|
||||
for i = 1, purchase_count do
|
||||
total_amount = total_amount + purchases[i].amount
|
||||
end
|
||||
|
||||
local user_count = 0
|
||||
for user, _ in pairs(users) do
|
||||
user_count = user_count + 1
|
||||
end
|
||||
|
||||
print(" Statistics:")
|
||||
print(" - Total users: " .. user_count)
|
||||
print(" - Total purchases: " .. purchase_count)
|
||||
print(" - Total revenue: $" .. string.format("%.2f", total_amount))
|
||||
print(" - Average purchase: $" .. string.format("%.2f", total_amount / purchase_count))
|
||||
|
||||
-- Log file processing
|
||||
print("\n5. Log Processing:")
|
||||
log_content = `tail -20 /var/log/system.log 2>/dev/null || echo "Log not accessible"`
|
||||
if log_content ~= "Log not accessible" then
|
||||
print(" Recent system log entries found")
|
||||
else
|
||||
-- Create a sample log for demonstration
|
||||
sample_log = [[2024-01-01 10:00:01 INFO: Application started
|
||||
2024-01-01 10:00:05 DEBUG: Database connection established
|
||||
2024-01-01 10:00:10 WARN: High memory usage detected
|
||||
2024-01-01 10:00:15 ERROR: Failed to connect to external API
|
||||
2024-01-01 10:00:20 INFO: Retrying API connection
|
||||
2024-01-01 10:00:25 INFO: API connection restored]]
|
||||
|
||||
local log_file = io.open("sample.log", "w")
|
||||
log_file:write(sample_log)
|
||||
log_file:close()
|
||||
|
||||
print(" Created sample.log for demonstration")
|
||||
print(" Log analysis:")
|
||||
|
||||
-- Count log levels
|
||||
error_count = `grep -c "ERROR" sample.log`
|
||||
warn_count = `grep -c "WARN" sample.log`
|
||||
info_count = `grep -c "INFO" sample.log`
|
||||
|
||||
print(" - Errors: " .. error_count)
|
||||
print(" - Warnings: " .. warn_count)
|
||||
print(" - Info messages: " .. info_count)
|
||||
end
|
||||
|
||||
-- Text transformation
|
||||
print("\n6. Text Transformation:")
|
||||
input_text = "Hello World, this is a TEST message"
|
||||
|
||||
-- Using shell commands for text processing
|
||||
upper_text = `echo "` .. input_text .. `" | tr '[:lower:]' '[:upper:]'`
|
||||
print(" Uppercase: " .. upper_text)
|
||||
|
||||
word_count = `echo "` .. input_text .. `" | wc -w`
|
||||
print(" Word count: " .. word_count)
|
||||
|
||||
-- Using Lua for more complex transformations
|
||||
words = {}
|
||||
for word in input_text:gmatch("%w+") do
|
||||
table.insert(words, word)
|
||||
end
|
||||
|
||||
print(" Words: " .. table.concat(words, ", "))
|
||||
print(" Reversed: " .. table.concat(words, " "):reverse())
|
||||
|
||||
-- Batch file processing
|
||||
print("\n7. Batch Processing:")
|
||||
-- Create multiple sample files
|
||||
for i = 1, 3 do
|
||||
local batch_file = io.open("batch_" .. i .. ".txt", "w")
|
||||
batch_file:write("Sample content for file " .. i .. "\n")
|
||||
batch_file:write("Line 2 of file " .. i .. "\n")
|
||||
batch_file:close()
|
||||
end
|
||||
|
||||
print(" Created 3 batch files")
|
||||
|
||||
-- Process all batch files
|
||||
batch_files = `ls batch_*.txt`
|
||||
total_lines = 0
|
||||
|
||||
for filename in batch_files:gmatch("[^\n]+") do
|
||||
local lines = `wc -l < ` .. filename
|
||||
total_lines = total_lines + tonumber(lines)
|
||||
print(" " .. filename .. ": " .. lines .. " lines")
|
||||
end
|
||||
|
||||
print(" Total lines across all files: " .. total_lines)
|
||||
|
||||
-- Cleanup
|
||||
print("\n8. Cleanup:")
|
||||
!rm -f sample_data.csv sample.log batch_*.txt
|
||||
print(" Temporary files cleaned up")
|
||||
|
||||
print("\n✓ Data processing demo completed!")
|
||||
118
examples/07_interactive_demo.luash
Normal file
118
examples/07_interactive_demo.luash
Normal file
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env luash
|
||||
-- Interactive Luash Demo/REPL Alternative
|
||||
-- Shows how to build interactive features within luash
|
||||
|
||||
print("🚀 Luash Interactive Demo")
|
||||
print("This demonstrates interactive capabilities in luash")
|
||||
print()
|
||||
|
||||
-- Simple command processor
|
||||
function process_command(cmd)
|
||||
cmd = cmd:match("^%s*(.-)%s*$") -- trim
|
||||
|
||||
if cmd == "help" then
|
||||
print([[
|
||||
Available commands:
|
||||
sysinfo - Show system information
|
||||
files - List files in current directory
|
||||
env - Show environment variables
|
||||
network - Test network connectivity
|
||||
processes - Show running processes
|
||||
disk - Show disk usage
|
||||
quit - Exit
|
||||
|
||||
Or type any luash expression!]])
|
||||
|
||||
elseif cmd == "sysinfo" then
|
||||
print("System Information:")
|
||||
print(" OS: " .. `uname -s`)
|
||||
print(" Architecture: " .. `uname -m`)
|
||||
print(" Hostname: " .. `hostname`)
|
||||
print(" User: " .. $USER)
|
||||
print(" Uptime: " .. `uptime`)
|
||||
|
||||
elseif cmd == "files" then
|
||||
print("Files in current directory:")
|
||||
files = `ls -la`
|
||||
print(files)
|
||||
|
||||
elseif cmd == "env" then
|
||||
print("Key environment variables:")
|
||||
print(" USER: " .. $USER)
|
||||
print(" HOME: " .. $HOME)
|
||||
print(" SHELL: " .. $SHELL)
|
||||
print(" PATH: " .. `echo $PATH | cut -d: -f1-3`)
|
||||
|
||||
elseif cmd == "network" then
|
||||
print("Network connectivity test:")
|
||||
hosts = {"google.com", "github.com"}
|
||||
for i = 1, #hosts do
|
||||
local host = hosts[i]
|
||||
local result = `ping -c 1 #{host} >/dev/null 2>&1 && echo "ok" || echo "fail"`
|
||||
local status = result == "ok" and "✓" or "✗"
|
||||
print(" " .. status .. " " .. host)
|
||||
end
|
||||
|
||||
elseif cmd == "processes" then
|
||||
print("Top processes:")
|
||||
!ps aux | head -10
|
||||
|
||||
elseif cmd == "disk" then
|
||||
print("Disk usage:")
|
||||
!df -h
|
||||
|
||||
elseif cmd == "quit" or cmd == "exit" then
|
||||
return false
|
||||
|
||||
else
|
||||
-- Try to execute as luash code
|
||||
if cmd ~= "" then
|
||||
print("Executing: " .. cmd)
|
||||
-- In a real REPL, we'd eval this
|
||||
-- For demo, just show some dynamic examples
|
||||
if cmd:match("^%$") then
|
||||
print("Environment variable assignment")
|
||||
elseif cmd:match("`.*`") then
|
||||
print("Shell command execution")
|
||||
else
|
||||
print("Lua expression")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
-- Main interaction loop
|
||||
print("Type 'help' for commands, 'quit' to exit")
|
||||
print()
|
||||
|
||||
-- Simulate some interactive commands
|
||||
commands = {
|
||||
"help",
|
||||
"sysinfo",
|
||||
"files",
|
||||
"network",
|
||||
"quit"
|
||||
}
|
||||
|
||||
for i = 1, #commands do
|
||||
local cmd = commands[i]
|
||||
print("luash> " .. cmd)
|
||||
|
||||
if not process_command(cmd) then
|
||||
break
|
||||
end
|
||||
|
||||
if i < #commands then
|
||||
print("\nPress Enter to continue...")
|
||||
io.read() -- Wait for user input
|
||||
end
|
||||
end
|
||||
|
||||
print("\n✨ This shows how luash can build interactive applications!")
|
||||
print("For a full REPL, we'd:")
|
||||
print(" - Read input in a loop")
|
||||
print(" - Parse and execute luash expressions")
|
||||
print(" - Handle multiline input")
|
||||
print(" - Maintain command history")
|
||||
71
examples/08_repl_guide.luash
Normal file
71
examples/08_repl_guide.luash
Normal file
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env luash
|
||||
-- REPL Demo: Showcasing interactive features
|
||||
|
||||
print("🎮 Luash Interactive Shell Demo")
|
||||
print("===============================\n")
|
||||
|
||||
print("Luash now supports a full interactive REPL!")
|
||||
print("Start it with: ./luash -i")
|
||||
print()
|
||||
|
||||
print("🔥 REPL Features:")
|
||||
print("✓ All luash preprocessing ($VAR, `commands`, #{interpolation})")
|
||||
print("✓ Multiline input (functions, loops, if blocks)")
|
||||
print("✓ Command history")
|
||||
print("✓ Special dot commands (.help, .exit, .clear, .history)")
|
||||
print("✓ Real-time expression evaluation")
|
||||
print()
|
||||
|
||||
print("📝 Example REPL Session:")
|
||||
examples = {
|
||||
'print("Hello " .. $USER)',
|
||||
'$GREETING = "Hello from REPL"',
|
||||
'files = `ls *.luash | wc -l`',
|
||||
'print("Found " .. files .. " luash files")',
|
||||
'host = "google.com"',
|
||||
'status = `ping -c 1 #{host} >/dev/null && echo "ok"`',
|
||||
'print(host .. " is " .. status)',
|
||||
'',
|
||||
'-- Multiline example:',
|
||||
'for i = 1, 3 do',
|
||||
' print("Iteration: " .. i)',
|
||||
'end',
|
||||
'',
|
||||
'-- Function definition:',
|
||||
'function greet(name)',
|
||||
' return "Hello, " .. name .. "!"',
|
||||
'end',
|
||||
'',
|
||||
'print(greet($USER))'
|
||||
}
|
||||
|
||||
for i, example in ipairs(examples) do
|
||||
if example == "" then
|
||||
print()
|
||||
elseif example:match("^%-%-") then
|
||||
print(example)
|
||||
else
|
||||
print("luash> " .. example)
|
||||
end
|
||||
end
|
||||
|
||||
print()
|
||||
print("🚀 Try it now: ./luash -i")
|
||||
print(" Or: ./luash --interactive")
|
||||
print()
|
||||
|
||||
print("💡 The REPL supports:")
|
||||
print(" • Environment variables: $HOME, $USER, etc.")
|
||||
print(" • Shell commands: `ls`, `pwd`, `date`")
|
||||
print(" • Variable interpolation: `echo #{variable}`")
|
||||
print(" • Interactive commands: !git status")
|
||||
print(" • Full Lua: functions, loops, tables, etc.")
|
||||
print(" • Command history and editing")
|
||||
print()
|
||||
|
||||
print("✨ Perfect for:")
|
||||
print(" • Interactive system administration")
|
||||
print(" • Exploring file systems and processes")
|
||||
print(" • Quick shell command prototyping")
|
||||
print(" • Learning luash syntax")
|
||||
print(" • Debugging shell scripts")
|
||||
124
examples/09_showcase.luash
Normal file
124
examples/09_showcase.luash
Normal file
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env luash
|
||||
-- Luash Showcase: Highlight the best features
|
||||
|
||||
print("🚀 Luash - Minimal Lua Shell Scripting")
|
||||
print("=" .. string.rep("=", 45))
|
||||
|
||||
print("\n💡 Why Luash?")
|
||||
print("✓ Clean syntax - no more bash quoting nightmares")
|
||||
print("✓ Real programming language features")
|
||||
print("✓ Seamless shell integration")
|
||||
print("✓ Minimal and focused")
|
||||
|
||||
print("\n📊 Quick Comparison:")
|
||||
print("┌─────────────────┬─────────────────────┬─────────────────────┐")
|
||||
print("│ Task │ Bash │ Luash │")
|
||||
print("├─────────────────┼─────────────────────┼─────────────────────┤")
|
||||
print("│ Variables │ VAR=\"value\" │ $VAR = \"value\" │")
|
||||
print("│ Command Sub │ result=$(cmd) │ result = `cmd` │")
|
||||
print("│ Conditionals │ if [ -f file ]; fi │ if `test -f file` │")
|
||||
print("│ Arrays │ arr=(a b c) │ arr = {\"a\",\"b\",\"c\"} │")
|
||||
print("│ Functions │ Limited │ Full Lua functions │")
|
||||
print("└─────────────────┴─────────────────────┴─────────────────────┘")
|
||||
|
||||
print("\n🎯 Live Examples:")
|
||||
|
||||
print("\n1. Environment & Variables")
|
||||
print(" Current user: " .. $USER)
|
||||
$GREETING = "Hello from Luash"
|
||||
print(" Custom var: " .. $GREETING)
|
||||
|
||||
print("\n2. Shell Integration")
|
||||
system_info = `uname -a`
|
||||
print(" System: " .. system_info)
|
||||
|
||||
file_count = `ls | wc -l`
|
||||
print(" Files here: " .. file_count)
|
||||
|
||||
print("\n3. Real Programming")
|
||||
-- Lua's power: functions, tables, proper data types
|
||||
function analyze_directory(path)
|
||||
local files = `ls -la ` .. (path or ".")
|
||||
local lines = {}
|
||||
local file_count = 0
|
||||
local total_size = 0
|
||||
|
||||
for line in files:gmatch("[^\n]+") do
|
||||
if not line:match("^total") and not line:match("^d") then
|
||||
file_count = file_count + 1
|
||||
-- Extract size (5th field in ls -la)
|
||||
local size = line:match("%S+%s+%S+%s+%S+%s+%S+%s+(%d+)")
|
||||
if size then
|
||||
total_size = total_size + tonumber(size)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return file_count, total_size
|
||||
end
|
||||
|
||||
files, size = analyze_directory()
|
||||
print(" Analysis: " .. files .. " files, " .. size .. " bytes total")
|
||||
|
||||
print("\n4. Error Handling")
|
||||
if `which git 2>/dev/null` ~= "" then
|
||||
print(" ✓ Git is available")
|
||||
if `git status 2>/dev/null` ~= "" then
|
||||
branch = `git branch --show-current 2>/dev/null`
|
||||
print(" Current branch: " .. branch)
|
||||
else
|
||||
print(" Not in a git repository")
|
||||
end
|
||||
else
|
||||
print(" ✗ Git not installed")
|
||||
end
|
||||
|
||||
print("\n5. Data Processing")
|
||||
-- Create and process some data
|
||||
sample_data = {
|
||||
{name = "Alice", score = 95},
|
||||
{name = "Bob", score = 87},
|
||||
{name = "Charlie", score = 92}
|
||||
}
|
||||
|
||||
total_score = 0
|
||||
for i = 1, #sample_data do
|
||||
total_score = total_score + sample_data[i].score
|
||||
end
|
||||
average = total_score / #sample_data
|
||||
|
||||
print(" Student scores processed:")
|
||||
print(" Average: " .. string.format("%.1f", average))
|
||||
|
||||
-- Find highest scorer
|
||||
best_student = sample_data[1]
|
||||
for i = 2, #sample_data do
|
||||
if sample_data[i].score > best_student.score then
|
||||
best_student = sample_data[i]
|
||||
end
|
||||
end
|
||||
print(" Top student: " .. best_student.name .. " (" .. best_student.score .. ")")
|
||||
|
||||
print("\n🎪 Interactive Demo:")
|
||||
print(" Let's see what's running on your system...")
|
||||
!ps aux | head -5
|
||||
|
||||
print("\n📈 Performance:")
|
||||
start_time = `date +%s.%N`
|
||||
-- Simulate some work
|
||||
for i = 1, 1000 do
|
||||
local _ = string.upper("performance test " .. i)
|
||||
end
|
||||
end_time = `date +%s.%N`
|
||||
|
||||
-- Calculate duration (requires bash-style arithmetic)
|
||||
duration = tonumber(end_time) - tonumber(start_time)
|
||||
print(" Processed 1000 operations in " .. string.format("%.3f", duration) .. " seconds")
|
||||
|
||||
print("\n✨ Try these demos:")
|
||||
print(" ./luash demo_quick_examples.luash # Side-by-side with bash")
|
||||
print(" ./luash demo_system_admin.luash # Sysadmin tasks")
|
||||
print(" ./luash demo_development.luash # Dev workflows")
|
||||
print(" ./luash demo_data_processing.luash # Data analysis")
|
||||
|
||||
print("\n🎉 Luash: Shell scripting that doesn't make you cry!")
|
||||
36
examples/README.md
Normal file
36
examples/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Luash Examples
|
||||
|
||||
This directory contains examples demonstrating Luash features, organized in a logical learning order:
|
||||
|
||||
## 📚 Learning Path
|
||||
|
||||
1. **[01_basic_features.luash](01_basic_features.luash)** - Core Luash features (env vars, commands, strings)
|
||||
2. **[02_quick_comparison.luash](02_quick_comparison.luash)** - Side-by-side comparison with Bash
|
||||
3. **[03_interpolation.luash](03_interpolation.luash)** - Variable interpolation in shell commands
|
||||
4. **[04_system_admin.luash](04_system_admin.luash)** - System administration tasks
|
||||
5. **[05_development.luash](05_development.luash)** - Development workflows
|
||||
6. **[06_data_processing.luash](06_data_processing.luash)** - Data analysis and processing
|
||||
7. **[07_interactive_demo.luash](07_interactive_demo.luash)** - Building interactive applications
|
||||
8. **[08_repl_guide.luash](08_repl_guide.luash)** - Interactive shell usage guide
|
||||
9. **[09_showcase.luash](09_showcase.luash)** - Complete feature showcase
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
```bash
|
||||
# Run individual examples
|
||||
../luash 01_basic_features.luash
|
||||
|
||||
# Run the showcase (best overview)
|
||||
../luash 09_showcase.luash
|
||||
|
||||
# Try the interactive shell
|
||||
../luash -i
|
||||
```
|
||||
|
||||
## 📝 Example Categories
|
||||
|
||||
- **Basics**: Examples 1-3 cover fundamental syntax and features
|
||||
- **Use Cases**: Examples 4-6 show practical applications
|
||||
- **Advanced**: Examples 7-9 cover interactive features and comprehensive demos
|
||||
|
||||
Each example is self-contained and includes explanatory comments.
|
||||
Reference in New Issue
Block a user