lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

> A possibly useful addition to the repertoire of table iterators is
> "traverse", which recursively visits every non-table value in a table
> and returns not that value but a key-table pair (k,s) so that s[k]
> refers to the table entry.  This can be extended to allow the cloning
> of table structure and the simultaneous traversal of several tables.
> For example, this is a deep table copy:
>   t2={}
>   for k,s1,s2 in traverse(t1,t2) do s2[k]=s1[k] end

This is quite an interesting function, for:
- Performing a multiple deep table copy is very easy with the
function, but I think it is rarely needed.
- Comparing two tables with the same structure can be done easily in Lua.

BTW, for both tasks, the few times I have needed that feature, I used
table serialization. [1].
- To make a deep copy, serialize the first table and evaluate the
string for cloning
- To compare, serialize both tables to files and use a file comparison

But I would also like to use such a function to
- easily dump the table data to screen
- search for a particular data in a recursive table.

In both cases, we need to have *the context* of where the k,s1,s2
values can be found.
The better would be a table with a stack of keys (c in the next example).
So, one could write something like that to compare on screen two tables :

for k,c,s1,s2 in traverse(t1,t2) do
  print(  table.concat(c,"/"), s1[k], s2[k] )