From 1688a712cb863ab9492a24ae542294750fe38ec2 Mon Sep 17 00:00:00 2001 From: whosit Date: Tue, 25 Mar 2025 00:28:33 +0300 Subject: [PATCH] provide dir and dir2 functions for listing table keys Both functions don't expand tables used as keys/values. `dir(table)` will list `key = value` pairs, but non-recursively. `dir2(table)` will only list the keys. These functions return nothing and are to be used only interactively. --- dump.lua | 33 ++++++++++++++++++++++++++++++++- init.lua | 15 ++++++++++----- 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/dump.lua b/dump.lua index 670ad21..b1b2518 100644 --- a/dump.lua +++ b/dump.lua @@ -119,4 +119,35 @@ local function repl_dump(o, indent, nested, level) return "{"..table.concat(ret, ", ").."}" end -return repl_dump + +local function dump_dir(o) + -- dump only top-level key = value pairs + local t = type(o) + if t ~= "table" then + return basic_dump(o) + end + + local ret = {} + local dumped_indexes = {} + for i, v in ipairs(o) do + ret[#ret + 1] = string.format("[%s] = %s", i, basic_dump(v)) + dumped_indexes[i] = true + end + for k, v in pairs(o) do + if not dumped_indexes[k] then + if type(k) ~= "string" or not is_valid_identifier(k) then + k = "["..basic_dump(k).."]" + end + v = basic_dump(v) + ret[#ret + 1] = k.." = "..v + end + end + return "{\n "..table.concat(ret, ",\n ").."\n}" +end + +local dump_funcs = { + repl_dump = repl_dump, + dump_dir = dump_dir, +} + +return dump_funcs diff --git a/init.lua b/init.lua index d816e56..0d865ba 100644 --- a/init.lua +++ b/init.lua @@ -2,7 +2,9 @@ local MODNAME = core.get_current_modname() local MODPATH = core.get_modpath(MODNAME) local util = dofile(MODPATH .. DIR_DELIM .. "util.lua") -local repl_dump = dofile(MODPATH .. DIR_DELIM .. "dump.lua") +local dump_funcs = dofile(MODPATH .. DIR_DELIM .. "dump.lua") +local repl_dump = dump_funcs.repl_dump +local dump_dir = dump_funcs.dump_dir local api = {} _G[MODNAME] = api @@ -85,11 +87,14 @@ local function create_shared_environment(player_name) end core.chat_send_player(player_name, msg) end, - dir = function(t) - -- collect all keys of the table - if type(t) == "table" then + dir = function(o) + core.chat_send_player(player_name, dump_dir(o)) + end, + dir2 = function(o) + -- collect all keys of the table, no values + if type(o) == "table" then local keys = {} - for k, _ in pairs(t) do + for k, _ in pairs(o) do local key = k local t = type(key) if t == "string" then