Core Lua Scripting Techniques

Invoking Lua from the Shell

Lua modules can be executed directly via the command line interface without creating a separate script file. This is useful for quick tasks or integrating with system workflows.

lua -e "require('sys.network').verify('127.0.0.1')"

Processing Command Line Arguments

When a script is executed, arguments are stored in the global arg table. The index 0 typically holds the script path, while subsequent indices contain passed parameters. There is no explicit argument count variable; instead, the length operator determines the size.

#!/usr/bin/env lua

local function process_inputs()
    local script_path = arg[0]
    local total_params = #arg
    
    io.write(string.format("Running: %s\n", script_path))
    
    for i = 1, total_params do
        io.write(string.format("Param %d: %s\n", i, arg[i]))
    end
end

process_inputs()

Execution example:

$ lua script.lua alpha beta
Running: script.lua
Param 1: alpha
Param 2: beta

Time and Date Operations

Standard libraries provide multiple ways to handle temporal data, ranging from UNIX timestamps to formatted strings.

UNIX Timestamps

local current_epoch = os.time()
print(current_epoch)
-- Output: 1700638601

Formatted Dates

The os.date function supports formatting codes. If no arguments are provided, it returns a human-readable string. Timezone conversion is handled automatically based on system settings.

print(os.date())
-- Output: Wed Nov 22 15:36:41 2023

print(os.date("%H:%M:%S"))

local formatted = os.date("%Y-%m-%d %H:%M:%S", os.time())

High Precision Timing

For mircosecond precision, the socket library offers higher resolution timers.

local socket = require("socket")
local precise_time = socket.gettime()
print(string.format("Time: %.4f", precise_time))
-- Output: Time: 1700638361.9353

Iterating Over Tables

Lua provides two primary iterators for tables. ipairs is designed for sequential arrays with integer keys, stopping at the first nil value. pairs iterates over all key-value pairs regardless of type.

Sequential Arrays

local sequence = {"x", "y", "z"}

for idx, val in ipairs(sequence) do
    print(idx, val)
end

Key-Value Mapps

Whenn using non-integer keys, ipairs will not yield results, whereas pairs will traverse the entire hash table.

local config = {
    host = "localhost",
    port = 8080
}

for k, v in pairs(config) do
    print(k, v)
end

-- ipairs(config) would produce no output here

String Manipulation

The string library offers robust tools for extraction, replacement, and pattern matching. Methods can be called via the library or using colon syntax on string objects.

Substring Extraction

local text = "Lua Programming"
local part = text:sub(1, 3)
print(part) -- Output: Lua

Global Substitution

local source = "Hello World"
local target = source:gsub("World", "Universe")
print(target) -- Output: Hello Universe

Pattern Matching

match returns the first capture, while gmatch returns an iterator for all captures.

local data = "ID: 12345"
local id = string.match(data, "%d+")

if id then
    print(id)
end

Iterating over multiple matches:

local sentence = "one two one"
for word in string.gmatch(sentence, "%w+") do
    print(word)
end

Generating Random Numbers

To ensure variability, seed the generator with the current time before requesting a value within a specific range.

math.randomseed(os.time())
local random_val = math.random(1, 1000)

File Input and Output

File operations rely on the io library. It is best practice to verify the file handle before attempting read or write operations.

Reading Content

local function load_config(path)
    local handle = io.open(path, "r")
    local result = nil
    
    if not handle then
        print("Failed to open:", path)
        return nil
    end
    
    local content = handle:read("*a")
    handle:close()
    
    if content then
        result = json.decode(content)
    end
    
    return result
end

Writing Content

local function save_config(path, data)
    local handle = io.open(path, "w")
    
    if not handle then
        print("Failed to open:", path)
        return false
    end
    
    handle:write(json.encode(data))
    handle:close()
    return true
end

Tags: Lua Scripting system-automation programming

Posted on Thu, 27 Aug 2026 16:09:27 +0000 by yandoo