Skip to content
Unsourced Pyramid edited this page Dec 26, 2024 · 1 revision

Lua Lenses API Documentation

Constructor Functions

lenses.lens(...)

Creates a lens from a sequence of keys.

Signature:

function lenses.lens(...) -> Lens

Parameters:

  • ...: Variable number of strings or functions representing path segments
    • String: Direct table key
    • Function: Dynamic key resolver function(table) -> key

Returns:

  • Lens: A new lens object

Example:

-- Simple key path
local lens1 = lenses.lens("user", "profile", "name")

-- With dynamic key
local lens2 = lenses.lens("users", function(t) return t.currentIndex end)

lenses.path(pathString)

Creates a lens from a dot-separated string path.

Signature:

function lenses.path(pathString: string) -> Lens

Parameters:

  • pathString: String with dot-separated path segments

Returns:

  • Lens: A new lens object

Example:

local lens = lenses.path("user.profile.settings.theme")

lenses.key(key)

Creates a lens focusing on a single key.

Signature:

function lenses.key(key: string|function) -> Lens

Parameters:

  • key: String or function for key resolution

Returns:

  • Lens: A new lens object

Example:

local lens = lenses.key("name")
local dynamicLens = lenses.key(function(t) return t.activeKey end)

lenses.with_opts(keys, options)

Creates a configured lens with specific behavior options.

Signature:

function lenses.with_opts(keys: table, options: table) -> Lens

Parameters:

  • keys: Array of path segments (strings or functions)
  • options: Configuration table
    • strict: boolean (default: false) - Throw errors on invalid paths
    • createMissing: boolean (default: false) - Auto-create missing tables

Returns:

  • Lens: A new lens object

Example:

local lens = lenses.with_opts(
    {"user", "settings"},
    {
        strict = true,
        createMissing = true
    }
)

lenses.array_wildcard([options])

Creates a lens that operates on all numeric indices.

Signature:

function lenses.array_wildcard(options?: table) -> Lens

Parameters:

  • options: Optional configuration table (same as with_opts)

Returns:

  • Lens: A new lens object

Example:

local lens = lenses.array_wildcard()
local items = lens:get({1, 2, 3}) -- Returns {1, 2, 3}

Lens Methods

lens:get(data)

Retrieves focused value from data structure.

Signature:

function lens:get(data: table) -> any

Parameters:

  • data: Table to read from

Returns:

  • The focused value, or nil if not found (non-strict mode)

Throws:

  • In strict mode:
    • When accessing non-existent key
    • When traversing non-table value

Example:

local lens = lenses.path("user.name")
local name = lens:get({user = {name = "John"}}) -- Returns "John"

lens:set(data, value)

Updates focused value in data structure (mutating).

Signature:

function lens:set(data: table, value: any)

Parameters:

  • data: Table to modify
  • value: New value to set

Throws:

  • In strict mode:
    • When path invalid
    • When intermediate value not table
    • When createMissing=false and path missing

Example:

local lens = lenses.path("user.name")
local data = {user = {}}
lens:set(data, "John") -- data.user.name is now "John"

lens:set_copy(data, value)

Creates new data structure with focused value updated.

Signature:

function lens:set_copy(data: table, value: any) -> table

Parameters:

  • data: Original table
  • value: New value to set

Returns:

  • New table with update applied

Throws:

  • Same conditions as set()

Example:

local lens = lenses.path("user.name")
local data = {user = {name = "John"}}
local newData = lens:set_copy(data, "Jane")
-- data unchanged, newData has new value

lens:and_then(otherLens)

Composes two lenses, creating deeper focus.

Signature:

function lens:and_then(otherLens: Lens) -> Lens

Parameters:

  • otherLens: Lens to compose with

Returns:

  • New composed lens

Example:

local userLens = lenses.key("user")
local nameLens = lenses.key("name")
local userNameLens = userLens:and_then(nameLens)

Operators

Concatenation (..)

Composes lenses using the concatenation operator.

Signature:

lens1 .. lens2 -> Lens

Example:

local userNameLens = lenses.key("user") .. lenses.key("name")

Types

Lens Object

Core lens object returned by constructors.

Properties:

  • strict: boolean - Whether lens operates in strict mode
  • createMissing: boolean - Whether lens auto-creates missing tables

Methods:

  • get(data)
  • set(data, value)
  • set_copy(data, value)
  • and_then(otherLens)

Error Handling

Strict Mode Errors

When strict = true, these conditions throw errors:

  1. Missing Key Error
local lens = lenses.with_opts({"a"}, {strict = true})
lens:get({}) -- Error: Key 'a' does not exist
  1. Non-Table Traversal Error
local lens = lenses.with_opts({"a", "b"}, {strict = true})
lens:get({a = 5}) -- Error: Attempt to index non-table
  1. Missing Intermediate Path Error
local lens = lenses.with_opts({"a", "b"}, {
    strict = true,
    createMissing = false
})
lens:set({}, "value") -- Error: Missing intermediate path

Common Patterns

Conditional Updates

local function updateIfExists(data, lens, value)
    if lens:get(data) ~= nil then
        return lens:set_copy(data, value)
    end
    return data
end

Safe Traversal

local function safeLens(path)
    return lenses.with_opts(path, {
        strict = false,
        createMissing = true
    })
end

Bulk Updates

local function updateAll(data, lens, values)
    local result = data
    for k, v in pairs(values) do
        result = lens:set_copy(result, v)
    end
    return result
end

Performance Notes

  1. Memory Usage:

    • set_copy creates new tables along path
    • Shallow copies only
    • No unnecessary copies of unaffected branches
  2. Computation Overhead:

    • Dynamic keys evaluated on each operation
    • Array wildcards iterate all numeric indices
    • Composition adds function call overhead
  3. Optimization Tips:

    • Cache composed lenses
    • Use set for bulk updates
    • Minimize dynamic key usage
    • Consider path depth in performance-critical code