Module:Test/sandbox
Jump to navigation
Jump to search
This page has been marked as needing documentation of its function and purpose. You can help RimWorld Wiki by creating it here |
local util = { _DESCRIPTION = 'an assortment of useful things', } --ref: https://gist.github.com/ripter/4270799 function util.tprint(tbl, indent) if not indent then indent = 0 end if type(tbl) ~= "table" then print(tbl) return 0 end for k, v in pairs(tbl) do formatting = string.rep(" ", indent) .. k .. ": " if type(v) == "table" then print(formatting) util.tprint(v, indent+1) elseif type(v) == 'boolean' then print(formatting .. tostring(v)) else print(formatting .. v) end end end --ref: http://lua-users.org/wiki/CopyTable function util.shallowcopy(original_table) local orig_type = type(original_table) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in pairs(original_table) do copy[orig_key] = orig_value end else -- number, string, boolean, etc copy = original_table end return copy end --ref: https://gist.github.com/balaam/3122129 function util.reverse_numeric_table(tbl) local reversed_table = {} local length = #tbl for i,v in ipairs(tbl) do reversed_table[length + 1 - i] = v end return reversed_table end ---procedure function util.hl(title, width) width = width or 80 if type(title) == "string" then title = " " .. title .. " " local before = math.floor((width - #title) / 2) local after = width - before - #title print(string.rep("-", before) .. title .. string.rep("-", after)) else print(string.rep("-", width)) end end function util.count(tbl, key_type) local length = 0; for k,v in pairs(tbl) do if key_type then if type(k) == key_type then length = length + 1 end else length = length + 1 end end return length end -- "delimiter" must be a single character or the removal of the final one won't work function util.table_to_csv_string(simple_table, delimiter) local f_name = "string_csv" delimiter = tostring(delimiter) or "," assert(#delimiter == 1, string.format("bad argument #2 to '%s' (single character expected)", f_name)) local list = "" for k,v in pairs(simple_table) do list = tostring(list) .. v .. delimiter end list = string.sub(list, 1, -2) return list end ---procedure -- this could be implemented with metatable events -- ignore_keys: {"foo", "bar", ... } function util.overwrite_first_table_with_second(first_table, second_table, ignore_keys) ignore_keys = ignore_keys or {} for k,v in pairs(second_table) do local ignore = false for _, ignored_key in ipairs(ignore_keys) do if k == ignored_key then ignore = true end end if not ignore then if type(v) == "table" then if type(first_table[k]) == "table" then util.overwrite_first_table_with_second(first_table[k], v) else first_table[k] = {} util.overwrite_first_table_with_second(first_table[k], v) end else first_table[k] = v end end end end return util