lua-users home
lua-l archive

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


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.

~Paige