summaryrefslogtreecommitdiff
path: root/09/ext.lua
blob: c1eb1cc04929726ee9534a5ae477b74ab84f5eb0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
-- Override tostring to display more info about the table
local old_tostring = tostring
local numtabs = 0
local printed_tables = {}

local function tostring_helper(el)
	assert(type(el) == "table", "Tried to call helper with something that was not a table, it was a " .. type(el))
	local mt = getmetatable(el)
	if mt and mt.__tostring then
		return mt.__tostring(el)
	elseif printed_tables[el] == true then
		return old_tostring(el)
	else
		printed_tables[el] = true
		numtabs = numtabs + 1
		local strbuilder = setmetatable({"{"},{__index = table})
		for k,v in pairs(el) do
			local key,value
			if type(k) == "table" then
				key = tostring_helper(k)
			else
				key = old_tostring(k)
			end
			if type(v) == "table" then
				value = tostring_helper(v)
			else
				value = old_tostring(v)
			end
			strbuilder:insert(string.format("%s%s : %s", string.rep("\t",numtabs), key, value))
		end
		strbuilder:insert(string.rep("\t",numtabs - 1) .. "}")
		numtabs = numtabs - 1
		return strbuilder:concat("\n")
	end

end
function tostring(el)
	printed_tables = {}
	if type(el) == "table" then
		return tostring_helper(el)
	end
	return old_tostring(el)
end

-- Functions to save my hands
function printf(fmt, ...)
	print(string.format(fmt,...))
end
function errorf(fmt, ...)
	--Our error isn't actually in this function, it's 1 above us (1) = 2
	error(string.format(fmt,...),2)
end
function assertf(bool, fmt, ...)
	assert(type(fmt) == "string", "Assertf arg #2 was \"" .. type(fmt) .. "\", expected string")
	if not bool then
		args = {fmt}
		for k,v in ipairs({...}) do
			table.insert(args,tostring(v))
		end
		error(string.format(unpack(args)),2)
	end
end