lua-users home
lua-l archive

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

2011/11/3 Leo Razoumov <>:
> Hi Francesco,
> thank you very much for your efforts!!!
> I will try GSL Shell v2 this weekend.

Thank you, Leo, I appreciate, it is very useful for me to have some

> Just one question. Have you found a efficient way to call Lua functions from C?
> For example, GSL quadrature functions take call-back function as
> input. In GSL shell, is it possible to pass a Lua function to be
> integrated? How does it work?
> Did you reimplemented GSL quadrature routines in pure Lua? How about ODEs?

Well, what I've done is to reimplement the quadrature routine in pure
Lua using the FFI interface. In this way I can completely avoid the
problem of the Lua/C/Lua transition with the callbacks. By writing the
routine in pure Lua code and using the FFI interface I can also
benefit of the ability of LuaJIT2 to generate native code.

The numeric integration routine are just a mere adaptation of the GSL
routines. For the moment I've implemented the QNG and QAG routines.
The implementation is in the file:

Please note that this is a template file but it is essentially plain
Lua code, the template system here is just used as smart preprocessor.

I've reimplemented in Lua also the ODE quadrature routines and the
Levemberg-Marquardt nonèlinear fit routines. For the non-linear fit
the result is completely finalized either in term of interface and in
term of correctness since it pass a subset of the NIST datasets and it
does match the output of the original GSL routines.

For the ODE is more complicated. I've implemented the
Runge-Kutta-Fehlberg 4(5) method and the Prince-Dormand 8(9) method
but using a different interface then GSL and I've made also several
modifications. The result is very good and we can even outpeform
optimized C code but the problem is that this implementation is
limited to systems with a small number of variables (something up to
12 or 20 may be). I didn't implement a version in array form just
because of lack of time but there are no major problems for its

The only problem for the ODE routines is that you may end up with a
different interface for systems in array form and this can be
Also with GSL 1.15 they have introduced a new ODE implementation with
more advanced routines based on the Jacobian and for the moment I
didn't implement this kind of routines.

So, to come back to your question, you can easily integrate Lua
function like that:

function f_gen(a, b)
  return function f(x)
           return exp(-a*x) * cos(b*x)

f = f_gen(0.1, 2.4)

num.integ(f, 0, 10)

And the execution speed will be very close or better of pure C implementation!