Skip to content

Utils.Fn

sravioli edited this page Oct 27, 2024 · 2 revisions

Overview

The Utils.Fn module offers a collection of utility functions designed to simplify common tasks in Lua, especially within the Wezterm environment. These functions provide functionality for table operations, function memoization, and other essential utilities.

Usage

local Utils = require "utils.fn"

-- Merging tables
local merged = Utils.tbl_merge({ a = 1 }, { b = 2 }, { c = 3 })

-- Memoizing a function
local memoized_value = Utils.gmemoize("my_key", function()
  return 42
end)
print(memoized_value()) -- Output: 42

Features

  • Table Merging: Combines multiple tables into one, handling nested tables.
  • Function Memoization: Caches function return values for improved performance.
  • Integration with Wezterm: Utilizes Wezterm’s global space for caching.

Class Structure

The Utils.Fn class consists of utility functions categorized into different areas of functionality.

Data Structures

The Utils.Fn class uses standard Lua tables and functions to provide its features. It does not introduce complex custom data structures but leverages Lua's built-in types effectively.

Utils.Fn

  • fs [Utils.Fn.FileSystem] - Functions related to file system operations.
  • mt [Utils.Fn.Maths] - Mathematical utility functions.
  • str [Utils.Fn.String] - String manipulation functions.
  • key [Utils.Fn.Keymap] - Key mapping functions.
  • color [Utils.Fn.Color] - Color-related functions.

Functions

.tbl_merge(t1, ...)

Merges two or more tables into the first table.

Parameters:

  • t1 [table] - base table to merge into.
  • ... [table[]] - one or more additional tables to merge with t1.

Returns:

  • t1 [table] - modified t1 table with contents of the other tables merged.

Example:

local t1 = { a = 1 }
local t2 = { b = 2 }
local t3 = { c = 3 }
local result = Utils.tbl_merge(t1, t2, t3)
print(result.b)  -- Output: 2

.gmemoize(key, value)

Memoizes the result of a function or value in Wezterm's global space.

Parameters:

  • key [string] - The key in the global space to store the memoized value.
  • value [any] - Either a function to memoize or a direct value.

Returns:

  • value [function|any] - A function that returns the cached value if value was a function; otherwise, returns the value directly.

Example:

local memoized = Utils.gmemoize("key", function() return os.time() end)
print(memoized())  -- Output: Cached timestamp

⚙️ Utils

Class
Functions
Clone this wiki locally