Useful Examples
A collection of practical Lune scripts for common tasks.
HTTP Requests
Section titled “HTTP Requests”Simple GET Request
Section titled “Simple GET Request”local net = require("@lune/net")
local response = net.request("https://api.github.com/users/octocat")
if response.ok then local data = net.jsonDecode(response.body) print("Name:", data.name) print("Bio:", data.bio)else print("Error:", response.statusCode, response.statusMessage)endPOST with JSON Body
Section titled “POST with JSON Body”local net = require("@lune/net")
local response = net.request({ url = "https://httpbin.org/post", method = "POST", headers = { ["Content-Type"] = "application/json", }, body = net.jsonEncode({ message = "Hello from Lune!", timestamp = os.time(), }),})
print("Response:", response.body)File Operations
Section titled “File Operations”Read and Process JSON File
Section titled “Read and Process JSON File”local fs = require("@lune/fs")local net = require("@lune/net")
-- Read JSON filelocal content = fs.readFile("config.json")local config = net.jsonDecode(content)
-- Modify and saveconfig.lastUpdated = os.date("%Y-%m-%d %H:%M:%S")
fs.writeFile("config.json", net.jsonEncode(config, true))print("Config updated!")List Files Recursively
Section titled “List Files Recursively”local fs = require("@lune/fs")
local function listFiles(dir, indent) indent = indent or "" for _, entry in ipairs(fs.readDir(dir)) do local path = dir .. "/" .. entry local isDir = fs.isDir(path) print(indent .. (isDir and "📁 " or "📄 ") .. entry) if isDir then listFiles(path, indent .. " ") end endend
listFiles(".")Process Management
Section titled “Process Management”Run System Command
Section titled “Run System Command”local process = require("@lune/process")
local result = process.exec("git", { "status" })
if result.ok then print("Git output:") print(result.stdout)else print("Error:", result.stderr)endBuild Script with Multiple Commands
Section titled “Build Script with Multiple Commands”local process = require("@lune/process")local fs = require("@lune/fs")
local function run(cmd, args) print("→ Running:", cmd, table.concat(args or {}, " ")) local result = process.exec(cmd, args or {}) if not result.ok then error("Command failed: " .. result.stderr) end return result.stdoutend
-- Clean build directoryif fs.isDir("build") then fs.removeDir("build")endfs.writeDir("build")
-- Run build stepsrun("npm", { "install" })run("npm", { "run", "build" })
print("✅ Build complete!")Async and Tasks
Section titled “Async and Tasks”Parallel HTTP Requests
Section titled “Parallel HTTP Requests”local net = require("@lune/net")local task = require("@lune/task")
local urls = { "https://api.github.com/users/octocat", "https://api.github.com/users/torvalds", "https://api.github.com/users/gaearon",}
local results = {}
-- Spawn parallel requestsfor i, url in ipairs(urls) do task.spawn(function() local response = net.request(url) if response.ok then results[i] = net.jsonDecode(response.body) end end)end
-- Wait for all to completetask.wait(2)
-- Print resultsfor i, data in pairs(results) do print(i, data.name, data.followers, "followers")endPeriodic Task
Section titled “Periodic Task”local task = require("@lune/task")local datetime = require("@lune/datetime")
local function checkHealth() print("[" .. datetime.now():formatLocalTime("%H:%M:%S") .. "] Health check...") -- Add your health check logic hereend
-- Run every 5 secondswhile true do checkHealth() task.wait(5)endSQLite Database
Section titled “SQLite Database”Simple Database Operations
Section titled “Simple Database Operations”local sql = require("@lune/sql")
-- Create or open databaselocal db = sql.open("myapp.db")
-- Create tabledb:execute([[ CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE, created_at DATETIME DEFAULT CURRENT_TIMESTAMP )]])
-- Insert datadb:execute("INSERT INTO users (name, email) VALUES (?, ?)", "John Doe", "john@example.com")
-- Query datalocal users = db:query("SELECT * FROM users WHERE name LIKE ?", "%John%")for _, user in ipairs(users) do print(user.id, user.name, user.email)end
db:close()Regex Pattern Matching
Section titled “Regex Pattern Matching”Extract Data with Regex
Section titled “Extract Data with Regex”local regex = require("@lune/regex")local fs = require("@lune/fs")
-- Read log filelocal log = fs.readFile("server.log")
-- Find all IP addresseslocal ipPattern = regex.new([[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}]])
for match in ipPattern:gmatch(log) do print("Found IP:", match:getText())end
-- Find all timestampslocal timePattern = regex.new([[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}]])
for match in timePattern:gmatch(log) do print("Found Time:", match:getText())endCLI Tool Template
Section titled “CLI Tool Template”Complete CLI Script
Section titled “Complete CLI Script”local process = require("@lune/process")local fs = require("@lune/fs")local stdio = require("@lune/stdio")
local args = process.args
local function printHelp() print([[Usage: lune run cli-tool [command] [options]
Commands: init Initialize a new project build Build the project clean Clean build artifacts help Show this help message ]])end
local function init() print("Initializing project...") fs.writeDir("src") fs.writeFile("src/main.luau", '-- Main file\nprint("Hello!")') print("✅ Project initialized!")end
local function build() print("Building...") -- Add build logic print("✅ Build complete!")end
local function clean() if fs.isDir("build") then fs.removeDir("build") print("✅ Cleaned build directory") else print("Nothing to clean") endend
-- Parse commandlocal command = args[1] or "help"
if command == "help" then printHelp()elseif command == "init" then init()elseif command == "build" then build()elseif command == "clean" then clean()else print("Unknown command:", command) printHelp() process.exit(1)endNext Steps
Section titled “Next Steps”- Learn more about each module in the API Reference
- Read The Book for in-depth tutorials
- Explore Roblox integration for game development