lua-users home
lua-l archive

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


> From: "Tobias Käs" <tobias.kaes@gmx.de>
>
> The reason is, there are many ways to copy a table, and you cannot define
a
> simple "standard" way.

    I believe copying the tables are the simple part.  The questions is what
is done with non-table keys and values.

> An example is: How is table recursion handled? The way you want to deal
with
> this is application dependant.

    Wouldn't general consensus be to recursively make copies of nested
tables or just take a reference to them?

> Another example is userdata: A reference copy
> may not be the desired thing to do.

    This is defiantly a more difficult issue but i don't think it's
impossible to consider some flexibility to allow for it.  A table copy
function could take three parameters like...

function table.copy( self, deep, ud_copy_fn )

    ud_copy_fn = ud_copy_fn or function ( ud ) return ud end

    local new_table = {}

    for key, value in self do

        local new_key
        if ( deep and type( key ) == 'table' ) then
            new_key = table.copy( key, deep, ud_copy_fn )
        elseif ( type( key ) == 'userdata' ) then
            new_key = ud_copy_fn( key )
        else
            new_key = key
        end

        local new_value
        if ( deep and type( value ) == 'table' ) then
            new_value = table.copy( value, deep, ud_copy_fn )
        elseif ( type( value ) == 'userdata' ) then
            new_value = ud_copy_fn( value )
        else
            new_value = value
        end

        new_table[ new_key ] = new_value
    end

     return new_table
end

    An option to not copy the keys could even be added without much
difficulty.

> It's simple to write a function of your own, and there are also several
> mailed to this list, just search.

    IMO Lua needs to have alot more common functionality included into the
standard library to support new and veteran programmers alike. Writing your
own, even if it's easy, is not productive and is going to introduce bugs.

    Tom