lua-users home
lua-l archive

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


For a very good table copying function see....

http://tcs01.les.inf.puc-rio.br/wiki/w/LuaLanguage/ScriptSandboxing

OK, included directly here.
Kudos to Pedro Miller Rabinovitch and Rici Lake.
The root problem is that since some variables are accessed by reference
rather than value, a "first level" copy of a table using next (or similar)
is incomplete.  This "Lazy copy" method arranges for "deeper copying" on an
as needed basis.  Of course, no "copying" is arranged for userdata's or
functions, only for tables.  However, I personally see no disadvantage in
the case of functions (because I know of no way to modify a function, so a
duplicate reference may as well be a duplicate copy).  As for userdata's,
well of course it all depends on the user data, and the best one could hope
for is a function/metamethod for copying.

--| Code sandboxing
--by Pedro Miller Rabinovitch <miller at inf.puc-rio.br>

local function lazy_copy( t )
        if type(t) ~= 'table' then return t end
        local nt, meta = {}, {}
        local t = t
        setmetatable( nt, meta )
        function meta:__index( idx )
                local v=t[idx]
                rawset( self, idx, v )
                return v
        end
        return nt
end


-----Original Message-----
From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br]On Behalf Of Robert
Anderberg
Sent: Sunday, November 16, 2003 1:19 PM
To: Lua list
Subject: Re: AW: Assignment of tables?


there are so many special cases that it's much easier to write your own
function eg:

function copyTable(_table)
  local newTable = {}
  for key,value in pairs(_table) do
    newTable[key] = value
  end
  return newTable
end


On Sunday 16 November 2003 7:14 pm, Jason P wrote:
> > > lets say I need to reset a table to some older state. Will this work?:
> > > MyTable = OlderTable;
> > > and what would happen to C refs which are attached to 'MyTable'?
> >
> >With the assignment you only assign a reference to the table.
> >After this instruction, both MyTable and OlderTable refer to the
> >same structure. If you change one, the change is visible from the
> >other, too.
> >
> >If MyTable was the only reference to that table, before you re-
> >assigned it, the table still stays in memory and will sometime
> >be collected by the garbage collector (at least at program exit).
> >
> >If there are other references left, nothing will happen to the table.
>
> ok, I understand. So there are no easy copytable() type abilities inside
> lua's base lib?
>
> _________________________________________________________________
> Send a QuickGreet with MSN Messenger
> http://www.msnmessenger-download.com/tracking/cdp_games