lua-users home
lua-l archive

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


On Sun, Apr 10, 2011 at 7:24 AM, Lorenzo Donati
<lorenzodonatibz@interfree.it> wrote:
> On 10/04/2011 10.45, Dirk Laurie wrote:
>>
>> On Sun, Apr 10, 2011 at 08:37:25AM +0200, Lorenzo Donati wrote:
>>>>
>>> Yes. I know that. But I avoid like the plauge to redefine standard
>>> libraries functions (even in short scopes - it's about readability).
>>>
>> Python does the various sorting options neatly: a.sort() sorts a in
>> place, sorted(a) returns a new array containing the sorted version
>> without disturbing the original.  OK, Python is a fat API, but that
>> sort of distinction aids clarity.
>>
>> Your argument against Sean's local redefinition of table.sort() does not
>> apply to making a new table.sorted().
>
> Of course that would be a little less intrusive change, but I still refrain
> to pollute standard namespaces with my tools.
>
> Please bear in mind that I didn't look for an alternative solution, (the
> solution is rather easy anyway). I, at the risk of being "heretic" :-), just
> suggested a small change in the API because I think it won't cause any
> problem and will add clarity (by avoiding needless temporaries) and some
> flexibility.
>
> I like Lua's approach, so I'm not a fan of language or API changes just
> because "Java/Python/C++/Snortlescript has it!" :-). The only objection to
> my proposal (which I think is in Lua's philosophy - but maybe I'm wrong
> here) was that of Luiz, but as I argued before, I'm not convinced by that
> alone (maybe there are other technical reasons for that choice?).
>
> I repeat: the simple difference between "in-place" vs. "new table", whereas
> important, is already stated extremely clearly in the docs and there are
> almost no sources of confusion with other API functions.

Here are my two favorite solutions (to the moment).
Note that I never define any function that copies the
table T before sorting it - T is always modified.

First the cleaner one:

  -- After running the line below we will have:
  --   table.sort  (T, comp) sorts T in-place and returns nil
  --   table.sorted(T, comp) sorts T in-place and returns T
  table.sorted = function (T, comp) table.sort(T, comp); return T end

And now a dirtier solution, in which we replace table.sort by a
slightly slower function, that returns the sorted table - but we only
do that if the current table.sort does not return anything.

  if not table.sort({}) then
    local table_sort_orig = table.sort
    table.sort = function (T, comp) table_sort_orig(T, comp); return T end
  end

Untested cheers,
  Eduardo Ochs
  eduardoochs@gmail.com
  http://angg.twu.net/