lua-users home
lua-l archive

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

On Sat, May 9, 2015 at 7:26 PM, Jay Carlson <> wrote:
> On May 9, 2015, at 7:10 PM, Coda Highland <> wrote:
>> On Sat, May 9, 2015 at 3:56 PM, Brigham Toskin <> wrote:
>>> On Sat, May 9, 2015 at 2:17 PM, Rena <> wrote:
>>>> But Lua also has some overhead with calling into C, doesn't it? So
>>>> some common operations are faster in pure Lua than in C? I'm sure I've
>>>> heard that.
>>> If it's a relatively small piece of code, the cost of calling into C could
>>> be higher than the cost of just running it in Lua. On the other hand, luajit
>>> produces native machine code, which could easily call a C function with
>>> relatively little overhead; I'm not sure what that actually ends up looking
>>> like, with bookkeeping and state fixups and stuff. Plus, as pointed out
>>> earlier, calling C functions probably foils optimizer traces, so I'm not
>>> sure it'll even do it.
>>> Does anybody know? Is Mike around?
> I like Coda's text enough that I'm going to steal it, and edit it in-place.
>> The JIT can't trace across Lua API calls because there are
>> absolutely no guarantees about the global state of Lua after a Lua API
>> function call -- the called function could do anything.
>> The LuaJIT FFI circumvents
>> this issue by prohibiting access to the Lua state during an FFI
>> function call.
> If I understand what you're saying:
> From the point of view of LuaJIT, FFI-functions are strict leaf calls. They can scribble on any C-world resources they want, but they can't mutate anything at all in the Lua world. All they can do is return a scalar.
> I suppose this just pushes the semantic complexity into the demarcation of C-world vs Lua-world.
> Jay

You understand correctly, although it's not STRICTLY limited to just a
scalar -- you can return a C struct just as well, and it'll be copied
into the Lua state and garbage-collected like any other Lua object.

In fact, C structs in LuaJIT are incredibly fast, and one of the first
suggestions for improving the performance of code in LuaJIT is to
switch from using tables to using structs when it's possible to do so
cleanly, even if you aren't invoking any FFI calls.

/s/ Adam