lua-users home
lua-l archive

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


Hi,

gary ng wrote:
> I am wondering if this has been discussed before that
> FP/HOF is good or just a waste of time in lua(say it
> is against its design or idioms or whatever).

Lua does not enforce a particular programming style. And in
general anything is good if it simplifies things (either for you
or the reader of your programs).

If you are comfortable programming in FP, then you are more
likely to produce better programs in this style. So yes, please
go ahead and use it.

> 1. performance wise, would it be better to use
> coroutine to simulate the "lazy" behaviour of generic
> iterators or using a closure to remember the states ? 

Lua coroutines are very fast, but closures still have a little
bit less activation overhead. I'd use closures mostly, and
coroutines only for problems that are better expressed with
control flow for state keeping.

> 2. the default behaviour of the for/loop iterators
> expect k,v pairs on each iteration, should this be in
> general adopted for custom iterators ?

Enforcing consistency is never wrong. Anything resembling an
iteration control variable (like a key) should go first because
it's passed back to the iterator. This avoids the overhead of
creating a stateful iterator in many cases. But if you need to
keep state anyway, then just be careful that the first result
must be non-nil unless you want to end the iteration.

BTW: the number of results is not limited to 2.

> 3. I believe for/loop should have the best performance
> comparing with repeat/while. But are their speed
> difference between repeat and while ?

Performance is best measured by benchmarking. Benchmarking your
own programs of course. Quick experiments like:

  time lua -e 'for i=1,1e8 do end'
  time lua -e 'local i=1; while i<=1e8 do i=i+1 end'
  time lua -e 'local i=0; repeat i=i+1 until i>=1e8'

can be very enlightening. But you really need to try it on
snippets of your own programs.

Note that these kind of tight loops suffer mainly from branch
prediction penalties due to the bytecode dispatch. This very much
depends on minor variations in coding (e.g. Lua 5.0 vs. 5.1) and
the kind of C compiler optimizations performed. Do not judge the
constructs solely based on an isolated measurement.

Other than that I'd choose loop constructs based on their
functionality and not based on their performance characteristics.
You can always tune the innermost loops later on (if you really
need to).

Bye,
     Mike