From dcadde38d77c5c9a77cf15eca2f2a90e8e764277 Mon Sep 17 00:00:00 2001 From: myk002 Date: Wed, 27 Apr 2022 12:16:53 -0700 Subject: [PATCH] add new global function: ensure_key --- docs/Lua API.rst | 6 ++++++ docs/changelog.txt | 1 + library/lua/dfhack.lua | 7 +++++++ 3 files changed, 14 insertions(+) diff --git a/docs/Lua API.rst b/docs/Lua API.rst index a0764df99..acc9174b1 100644 --- a/docs/Lua API.rst +++ b/docs/Lua API.rst @@ -2643,6 +2643,12 @@ environment by the mandatory init file dfhack.lua: Walks a sequence of dereferences, which may be represented by numbers or strings. Returns *nil* if any of obj or indices is *nil*, or a numeric index is out of array bounds. +* ``ensure_key(t, key[, default_value])`` + + If the Lua table ``t`` doesn't include the specified ``key``, ``t[key]`` is + set to the value of ``default_value``, which defaults to ``{}`` if not set. + The new or existing value of ``t[key]`` is then returned. + .. _lua-string: String class extentions diff --git a/docs/changelog.txt b/docs/changelog.txt index 9b449f4c9..adc25327a 100644 --- a/docs/changelog.txt +++ b/docs/changelog.txt @@ -91,6 +91,7 @@ changelog.txt uses a syntax similar to RST, with a few special sequences: - ``safe_index`` now properly handles lua sparse tables that are indexed by numbers - ``widgets``: unset values in ``frame_inset``-table default to ``0`` - ``dialogs``: ``show*`` functions now return a reference to the created dialog +- ``ensure_key``: new global function for retrieving or dynamically creating Lua table mappings # 0.47.05-r4 diff --git a/library/lua/dfhack.lua b/library/lua/dfhack.lua index 26e20f748..671029015 100644 --- a/library/lua/dfhack.lua +++ b/library/lua/dfhack.lua @@ -385,6 +385,13 @@ function safe_index(obj,idx,...) end end +function ensure_key(t, key, default_value) + if t[key] == nil then + t[key] = (default_value ~= nil) and default_value or {} + end + return t[key] +end + -- String class extentions -- prefix is a literal string, not a pattern