UserFunction; printTbl - HWRM/KarosGraveyard GitHub Wiki

printTbl(\<tbl\>, \<label\>)

Description

Prints all values in the given table, with a heading either equal to the address of the table or a given label.

If a value of tbl is itself a table, this function is called recursively.

Definition

--- Prints the key-value pairs of the given `tbl`.
---
--- This function works recursively on values which are themselves tables.
---
---@param tbl table
---@param label string
function printTbl(tbl, label)
	if (label == nil) then
		label = tostring(tbl)
	end

	---@param self function
	---@param tbl table
	---@param indent integer
	local _printTbl = function (self, tbl, indent)
		if (indent == nil) then
			indent = 0
		end
		local indent_str = ""
		if (indent > 0) then
			local cur_indents = 0
			while (cur_indents ~= indent) do
				indent_str = indent_str .. "\t"
				cur_indents = cur_indents + 1
			end
		end
		for k, v in tbl do
			if type(v) == "table" then
				print(indent_str .. "\"" .. k .. "\": {")
				self(self, v, indent + 1)
				print(indent_str .. "},")
			else
				if (type(v) ~= "number") then
					v = "\"" .. tostring(v) .. "\""
				end
				print(indent_str .. "\"" .. k .. "\": " .. v .. ',')
			end
		end
	end

	local temp_tbl = {}
	temp_tbl[label] = tbl
	_printTbl(_printTbl, temp_tbl)
end

Example

local t = {
  a = 10,
  b = "hey",
  c = {
    ca = 20,
    cb = "bye"
  }
};

printTbl(t, "cool table");

Arguments

Param Type Description
tbl table The table who's values will be printed.
label string? Optional header for printed output.

Related Functions

⚠️ **GitHub.com Fallback** ⚠️