Search code examples
c++luaffiluajit

Pre-optimize Lua script and call it later from C++


I have this filter engine, that I would like to script with LuaJIT, so that I can dump all the complicate parsing/eval code that I have.

My filter would be a string like this:

function filter ( obj ) return obj.attribute == "toto"

I would have something like this in my C++ code:

// on first pass:
if( ! cachedLuaFilter ) {
    // this will invoke the Lua parser to declare the function,
    // possibly triggering the JIT, and return the Lua parser 
    // with the function already pre-computed, 
    // waiting to be called with arguments. 
    cachedLuaFilter = createLuaFilter( "function filter ( obj ) return obj.attribute == \"toto\"" );
}
cachedLuaFilter->eval( myCPPObject ); // obj will be the FFI representation of myCPPObject

I have two questions:

  • can Lua pre-compile this function and let me call it with different C++ objects that have a FFI representation ?
  • is LuaJIT the right solution for that?

Solution

  • You can load it with loadstring or luaL_loadstring

    local filter = loadstring("local obj = ...; return obj.attribute")
    local attr = filter(someobj)
    -- Or:
    luaL_loadstring(L, "local obj = ...; return obj.attribute")
    

    Though I should clear up some misconceptions:

    • The Lua C API and LuaJIT's FFI don't mix. There are no C API functions for FFI objects; I'm not sure how you are passing one in.
    • LuaJIT is a trace compiler, not a method-at-a-time compiler. loadstring et al. will parse the source code to bytecode (which is still an improvement), but not machine code, which is only emitted in places where LuaJIT determines that it would give a major performance boost (usually inner loops).