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

2

7

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?

Plasmo answered 21/4, 2013 at 13:45 Comment(0)
M
13

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.

Maffa answered 21/4, 2013 at 15:11 Comment(3)
One other drawback to FFI functions is that they have no notion of the lua state they are called from, which doesn't help if you need to alter _GLOBAL in that env etc. also beware of C++ exceptions with the FFI.Trimly
Yes, but that's actually the difference between FFI and C/API. You define bindings on C side in case of Lua C API, whereas in case of FFI, you define them all from Lua side. And there you can alter global variables.Maffa
On the last paragraph - as in, the application is trying to provide APIs so that users can write scripts, and that is potentially unsafe with FFI, is it ?Pricilla
J
1

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.

Jolin answered 13/10, 2016 at 13:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.