Examples

Code That Ships and Works

Real examples you can copy, build, and run. Each example demonstrates specific Hype capabilities including plugins, and includes instructions for building standalone executables.

🚀 Quick Start Examples

🖥️ Hello World TUI

Simple terminal application to get started

-- hello.lua
local app = tui.newApp()
local textView = tui.newTextView("Hello, World from Lua!")
app:SetRoot(textView, true)
app:Run()
Build & Run:
hype build hello.lua -o hello && ./hello
View Source

🌐 HTTP Server

Web server with JSON API endpoints

-- server.lua
local http = require('http')
local server = http.newServer()

server:handle("/", function(req, res)
    res:write("Hello from Hype server!")
end)

server:handle("/api/test", function(req, res)
    res:json({message = "API works!", time = os.time()})
end)

server:listen(8080)
Build & Run:
hype build server.lua -o server && ./server
View Source

🔌 Plugin Usage

File operations using the filesystem plugin

-- plugin-demo.lua
local fs = require("fs")
local http = require('http')

-- Read config file
local config, err = fs.readFile("config.json")
if not config then
    config = '{"port": 8080}'
    fs.writeFile("config.json", config)
end

-- Create simple web server
local server = http.newServer()
server:handle("/", function(req, res)
    res:json({config = config, files = fs.listDir(".") or {}})
end)
server:listen(8080)
Build & Run:
hype build plugin-demo.lua --plugins fs@1.0.0 -o demo && ./demo
View Source

🔌 WebSocket Chat

Real-time chat server with message broadcasting

-- chat.lua
local websocket = require('websocket')
local clients = {}

local server = websocket.newServer()

server:handle("/chat", function(conn)
    table.insert(clients, conn)
    local clientId = #clients
    
    conn:onMessage(function(message)
        local msg = "Client " .. clientId .. ": " .. message.data
        -- Broadcast to all clients
        for i, client in ipairs(clients) do
            client:send(msg)
        end
    end)
    
    conn:onClose(function()
        -- Remove client from list
        for i, client in ipairs(clients) do
            if client == conn then
                table.remove(clients, i)
                break
            end
        end
    end)
end)

server:listen(8080)
Build & Run:
hype build chat.lua -o chat && ./chat
View Source

🔐 Cryptography Examples

🔑 Basic Crypto Operations

Key generation, signing, and verification with multiple algorithms

-- Generate different types of keys
local rsa_key = crypto.generate_jwk("RS256")
local ecdsa_key = crypto.generate_jwk("ES256") 
local ed25519_key = crypto.generate_jwk("EdDSA")

-- Sign and verify messages
local message = "Hello, secure world!"
local signature = crypto.sign(rsa_key, message)
local public_key = crypto.jwk_to_public(rsa_key)
local is_valid = crypto.verify(public_key, message, signature)

🔏 HTTP Signatures

Secure API communication with request/response signing

-- Sign HTTP requests
local request = {
    type = "request",
    method = "POST",
    path = "/api/users",
    headers = { ["Host"] = "api.example.com" },
    body = '{"name": "Alice"}'
}

local signed = httpsig.sign(request, {
    jwk = client_key,
    key_id = "client-key-2024",
    headers = {"(request-target)", "host", "digest"}
})

🔌 WebSocket Examples

💬 Echo Server

Simple WebSocket server that echoes messages back to clients

local websocket = require('websocket')
local server = websocket.newServer()

server:handle("/echo", function(conn)
    print("New WebSocket connection")
    
    conn:onMessage(function(message)
        print("Received:", message.data)
        -- Echo message back to client
        conn:send("Echo: " .. message.data)
    end)
    
    conn:onClose(function()
        print("Client disconnected")
    end)
    
    conn:onError(function(err)
        print("WebSocket error:", err)
    end)
    
    -- Send welcome message
    conn:send("Welcome to echo server!")
end)

server:listen(8080)
print("WebSocket server running at ws://localhost:8080/echo")

-- Keep server running
while true do
    os.execute("sleep 1")
end
Build & Run:
hype build echo-server.lua -o echo-server && ./echo-server
View Source

📡 WebSocket Client

Client that connects to WebSocket servers and handles real-time communication

local websocket = require('websocket')

-- Connect to WebSocket server
local client = websocket.connect("ws://localhost:8080/echo")

if not client then
    print("Failed to connect to WebSocket server")
    os.exit(1)
end

print("Connected to WebSocket server!")

-- Set up event handlers
client:onMessage(function(message)
    print("Received:", message.data)
    print("Message type:", message.type)  -- "text" or "binary"
end)

client:onClose(function()
    print("Connection closed")
end)

client:onError(function(err)
    print("WebSocket error:", err)
end)

-- Send test messages
client:send("Hello from Lua client!")
client:send("This is a test message")
client:sendBinary("Binary data")

-- Ping the server
client:ping()

-- Wait for responses
os.execute("sleep 2")

-- Close connection
client:close()
print("Client example completed")
Build & Run:
hype build ws-client.lua -o ws-client && ./ws-client
View Source

🌐 Multi-Client Chat Server

Real-time chat server that broadcasts messages to all connected clients

local websocket = require('websocket')
local clients = {}  -- Store connected clients

local server = websocket.newServer()

server:handle("/chat", function(conn)
    -- Add client to list
    table.insert(clients, conn)
    local clientId = #clients
    print("Client " .. clientId .. " connected")
    
    -- Send welcome message to new client
    conn:send("Welcome to the chat! You are client " .. clientId)
    
    -- Broadcast to all other clients
    for i, client in ipairs(clients) do
        if client ~= conn then
            client:send("Client " .. clientId .. " joined the chat")
        end
    end
    
    -- Handle incoming messages
    conn:onMessage(function(message)
        local msg = "Client " .. clientId .. ": " .. message.data
        print(msg)
        
        -- Broadcast message to all clients
        for i, client in ipairs(clients) do
            client:send(msg)
        end
    end)
    
    -- Handle client disconnect
    conn:onClose(function()
        -- Remove client from list
        for i, client in ipairs(clients) do
            if client == conn then
                table.remove(clients, i)
                break
            end
        end
        
        print("Client " .. clientId .. " disconnected")
        
        -- Notify other clients
        for i, client in ipairs(clients) do
            client:send("Client " .. clientId .. " left the chat")
        end
    end)
    
    conn:onError(function(err)
        print("Client " .. clientId .. " error:", err)
    end)
end)

server:listen(8080)
print("Chat server running at ws://localhost:8080/chat")
print("Connect multiple WebSocket clients to test")

-- Keep server running
while true do
    os.execute("sleep 1")
end
Test the Chat Server:
hype build chat-server.lua -o chat && ./chat

Use multiple browser tabs with JavaScript WebSocket clients to test

View Source

🔌 Plugin System Examples

📁 Filesystem Plugin

File operations with the built-in filesystem plugin

-- Use filesystem plugin
local fs = require("fs")

-- Read and write files
local content, err = fs.readFile("input.txt")
if content then
    fs.writeFile("output.txt", "Processed: " .. content)
end

-- Directory operations
local files = fs.listDir(".")
for _, file in ipairs(files or {}) do
    if fs.exists(file) then
        print("Size:", fs.size(file))
    end
end
Run with Plugin:
hype run example.lua --plugins fs@1.0.0
View Source

🔄 Multiple Plugins

Using multiple plugins in a single application

-- Use multiple plugins
local fs = require("fs")
local utils = require("utils")

-- Enhanced file operations
local data = fs.readFile("data.json")
if data then
    local processed = utils.processData(data)
    fs.writeFile("processed.json", processed)
end

-- Version information
print("FS Plugin Version:", fs.version())
print("Utils Plugin Version:", utils.version())
Run with Multiple Plugins:
hype run example.lua --plugins fs@2.0.0,utils@1.0.0
View Source

🖥️ Interactive Applications

🌐 Text-based Web Browser

Terminal browser with HTML-to-text conversion and navigation

Features: URL navigation, HTML parsing, interactive interface

View Source

📊 Advanced Dashboard

Real-time monitoring dashboard with database integration

Features: TUI interface, HTTP server, database logging, real-time updates

View Source

📂 Complete Example Collection

Browse all examples in the GitHub repository. Each includes source code, build instructions, and usage examples.

🔧 How to Use Examples

# Clone the repo
git clone https://github.com/twilson63/hype.git
cd hype/examples

# Run an example directly
hype run hello.lua

# Run with plugins
hype run test-fs-plugin.lua --plugins fs@1.0.0

# Build a standalone executable  
hype build hello.lua -o hello

# Build with embedded plugins
hype build test-fs-plugin.lua --plugins fs@1.0.0 -o fs-app

# Run the executable (zero dependencies!)
./hello
./fs-app