Skip to content

minify lua source code

Ingur Veken edited this page Jul 30, 2025 · 1 revision

This script serves as an example to show how you could minify your .lua source code files using luamin

#!/bin/bash
set -euo pipefail

# Minifies Lua source files in distribution packages
# Requires: npm install -g luamin

readonly PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly DIST_DIR="$PROJECT_ROOT/dist"
readonly EXCLUDE_FILES=()

log_info() {
    echo -e "\033[1;36m[INFO]\033[0m $@"
}

log_error() {
    echo -e "\033[1;31m[ERROR]\033[0m $@"
}

log_success() {
    echo -e "\033[1;32m[SUCCESS]\033[0m $@"
}

# Check if luamin is installed
if ! command -v luamin &> /dev/null; then
    log_error "luamin not found. Install with: npm install -g luamin"
    exit 1
fi

# Check if dist directory exists
if [ ! -d "$DIST_DIR" ]; then
    log_error "No dist directory found. Run './build.sh all zip' first."
    exit 1
fi

# Process each distribution zip
for zip_file in "$DIST_DIR"/*.zip; do
    [ ! -f "$zip_file" ] && continue
    [[ "$zip_file" == *"-minified.zip" ]] && continue
    
    zip_name="$(basename "$zip_file")"
    log_info "Processing $zip_name"
    
    # Create temp workspace
    temp_dir="/tmp/minify-$$-$(date +%s)"
    rm -rf "$temp_dir"
    mkdir -p "$temp_dir"
    
    # Extract main zip
    cd "$temp_dir"
    unzip -q "$zip_file"
    
    # Find game directory
    game_dir=$(ls -d */)
    game_dir=${game_dir%/}  # Remove trailing slash
    
    # Go to data directory
    cd "$game_dir/data"
    
    # Extract lua.zip
    unzip -q lua.zip
    
    # Go to lua directory
    cd lua
    
    # Minify Lua files
    minified_count=0
    for lua_file in *.lua; do
        # Skip excluded files
        if [[ " ${EXCLUDE_FILES[@]} " =~ " $lua_file " ]]; then
            log_info "  Skipping $lua_file (excluded)"
            continue
        fi
        
        # Minify file (exactly like test script)
        luamin -f "$lua_file" > "${lua_file}.tmp" 2>/dev/null || true
        
        # Check if minification succeeded
        if [ -s "${lua_file}.tmp" ]; then
            mv "${lua_file}.tmp" "$lua_file"
            minified_count=$((minified_count + 1))
            log_info "  ✓ Minified $lua_file"
        else
            rm -f "${lua_file}.tmp"
            log_error "  ✗ Failed to minify $lua_file"
        fi
    done
    
    # Go back to data directory
    cd ..
    
    # Remove old lua.zip and repack
    rm -f lua.zip
    zip -qr lua.zip lua
    
    # Remove lua directory
    rm -rf lua
    
    # Go back to temp root
    cd "$temp_dir"
    
    # Create minified distribution
    minified_name="${zip_name%.zip}-minified.zip"
    zip -qr "$DIST_DIR/$minified_name" "$game_dir"
    
    # Cleanup
    cd "$PROJECT_ROOT"
    rm -rf "$temp_dir"
    
    log_success "Created $minified_name ($minified_count files minified)"
done

log_success "Done!"

Clone this wiki locally