[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: params to __tostring
- From: Wesley Smith <wesley.hoke@...>
- Date: Sat, 10 Nov 2012 12:02:55 -0800
> Think for a moment why that wouldn't work -- the \t would only be
> added to the first line of a subtable.
Well, it doesn't take much work to indent a multi-line string:
local function indent(str, amt)
return str:gsub('\n', '\n'..amt)
end
local meta = {
__tostring = function(t)
local res = {}
for i=1, #t do
res[i] = string.format("\t%d = %s,", i, tostring(t[i]))
end
for k, v in pairs(t) do
if(type(k) ~= "number") then
res[#res+1] = indent(string.format("\t%s = %s,", k, tostring(v)), '\t')
end
end
return string.format("{\n%s\n}", table.concat(res, "\n"))
end
}
local t1 = setmetatable({
1, 2, 3, "four"
}, meta)
local t2 = setmetatable({
this = "that",
one = "two",
}, meta)
t1.t2 = t2
print(tostring(t1))