[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: params to __tostring
- From: spir <denis.spir@...>
- Date: Sat, 10 Nov 2012 19:50:32 +0100
On 10/11/2012 18:53, Kevin Martin wrote:
On 10 Nov 2012, at 12:25, spir wrote:
Is there a way to pass additional params to the function pointed by __tostring? (Would be practicle for instance to pass the set of already seen tables in stringing functions specialised for arrays, maps, objects, trees…)
I can't envisage an example of where this is necessary or useful. However, can you not just use an upvalue in your tostring to store previously passed values?
Thanks,
Kev
To print an array, object, whatever... in "tree view" with indentation, we need
to pass a nesting/indent level, and also the set of previously visited tables to
avoid inf recursion. If the function performing tostring for each type accepts
these parameters and deals with them, but __tostring does not forward them, then
we need to check the type of each sub-item to explicitely call this function,
instead of relying on the magic __tostring mechanism.
Or I miss a point.
For instance, if the top-level table is an array, to get the list of item
strings I could do something like:
local strings = {}
for _, item in ipairs(arr) do
strings[#strings + 1] = tostring(item, level, tables)
end
For now, I must specialise for every case, eg:
local strings = {}
local s
for _, item in ipairs(arr) do
if item.is_array then s = array_notation(item, level, tables)
elseif ...
elseif ...
elseif ...
end
strings[#strings + 1] = s
end
Denis