lua-users home
lua-l archive

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


2018-01-31 19:54 GMT+02:00 Paige DePol <lual@serfnet.org>:
> Dirk Laurie <dirk.laurie@gmail.com> wrote:
>
>> The Lua generic for is basically a C style expression loop.
>>
>> C:
>> void swap(int *a, int i, int j) {
>> int tmp = a[i];
>> a[i] = a[j]; a[j] = tmp;
>> }
>> for (i=0, j=n; i<j; a[i]>a[j]?swap(a,i,j):0, i++, j--);
>>
>>
>> Lua:
>> local i, j = 1,n;
>> for test in function(a) if i<j then
>>   if a[i]>a[j] then a[i],a[j] = a[j],a[i] end
>>   i,j = i+1,j-1;
>>   return true
>> end end, a do
>> end
>
> Yes, you can definitely implement an expression for loop
> as you've demonstrated, for your specific example, though
> personally I think the syntax is a bit more cumbersome.

Well, of course. Lua, like Pascal, sacrifices terseness for
readabilty. Both languages have in my opinion just the
right balance so that one's brain and fingers go at the
same rate.

But yes, the versatile all-purpose for loop (why on earth
does C have a while statement? saves two semicolons but
needs two extra letters) is the crown jewel of C syntax.