Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using Luajit, is it better to use FFI or normal lua bindings?

I just started tinkering with Luajit with C++ and I see that it's FFI is really easy to use but I am not sure if it is the best solution for all (or at least most) cases.

So is it better to use one or the other, or is it just preference?

like image 257
benbot Avatar asked Apr 21 '13 13:04

benbot


2 Answers

As it is stated on LuaJIT website, calls to C functions bound via FFI can be JIT compiled (as opposed to calls via Lua C/API), so in terms of performance FFI is definitely better. Moreover, using FFI you can use native C types for calculations in Lua, which can further benefit performance in certain cases (example).

One issue that you can have when using FFI (if you are used to C/API) is when you want a C function to return more than one value. In Lua C/API that's straightforward, but in case of FFI this requires some tricks (eg writing wrapper functions for FFI C calls). But I think this is a small drawback considering ease of use and performance that you get.

There are also some safety considerations, if your application allows for third party scripting, for example, as misusing FFI by them will happily crash your application without a warning.

like image 117
W.B. Avatar answered Nov 12 '22 14:11

W.B.


WRT to C++, here is a thread on the lua-l list about calling C++ which touches on this: http://lua-users.org/lists/lua-l/2011-07/threads.html#00492

In addition to WB's answer: it depends whether you are using the JIT compiler or the interpreter. You cannot run the JIT on some platforms (e.g iOS, due to licensing restrictions). It may therefore not be much faster to use the LuaJit FFI (as it is ~8-10x slower when using the interpreter), but then the LuaJit interpreter is 2-3 times faster than the Lua VM.

I'm also interested in calling C++ from Lua and am currently evaluating LuaJit. I generate Lua bindings using Ponder.

like image 1
Nick Avatar answered Nov 12 '22 13:11

Nick