[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: ipairs_remove - remove items from array while iterating it
- From: Francisco Olarte <folarte@...>
- Date: Sun, 3 Nov 2013 20:31:17 +0100
Hi David:
On Sun, Nov 3, 2013 at 12:49 PM, David Hamill <david@hamill.co.uk> wrote:
>> If you can spare enough memory for a copy of a list, you can do anything
>> you want by just processing it sequentially ...
> I'm new to Lua, but I've used Perl a lot; and Perl is also an interpreted
> language that uses tables ("hashes" or associative arrays) as a major data
> structure. My approach would be to copy the original table to a new one,
> leaving out the unwanted entries. Then the old table can be discarded, and
> hopefully it will be garbage-collected in due course.
I've used perl a lot too. Arrays will be what you'll use for list in
perl, unfortunately lua has only got tables, which really are like
hashes with some special magic to use them with integer keys. Anyway,
you cannot just discard the old table, you have to clear the original
one and copy the values into it, as you do not know who is referencing
the table from outside your scope. Vars in lua behave similar to
list/hash references in perl, and have similar problems. In perl, you
can, say zap every odd value from a list using a thing like this:
sub zap_odd_values {
my $src = shift;
my $ds=[]t;
for (my $i=0; $i<@$src;$i+=2) { push @$dst, $src[$i]; }
@$src = @$dst; // Copy it.
return;
}
this works if you do
$x=[0,1,2,3,4,5];
zap_odd_values($x);
if you returned the new list, you could assign to $x in the immediate
calling scope, but the real list behind may have a lot more
references.
> If plenty of memory is available, why not make use of it? But if memory is
> tight, one might not be able to afford the luxury of two large tables.
Also, in lua the extra large table costs in the order of 1 pointer per
entry, between 1 and 2 depending on fill factors if memory serves me
well, as it works pointer-like and every value is shared among the two
of them.
Francisco Olarte.