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.
This commit is contained in:
parent
b4c641bc57
commit
1688a712cb
33
dump.lua
33
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
|
||||
|
15
init.lua
15
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
|
||||
|
Loading…
Reference in New Issue
Block a user