预优化Lua脚本并稍后从C ++调用它

时间:2015-03-09 16:38:29

标签: c++ lua ffi luajit

我有这个过滤器引擎,我想用LuaJIT编写脚本,这样我就可以转储我拥有的所有复杂的解析/评估代码。

我的过滤器将是这样的字符串:

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

我的C ++代码中会有这样的东西:

// 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

我有两个问题:

  • Lua可以预先编译这个函数,让我用不同的具有FFI表示的C ++对象来调用它吗?
  • 是LuaJIT的正确解决方案吗?

1 个答案:

答案 0 :(得分:2)

您可以使用loadstringluaL_loadstring

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

虽然我应该澄清一些误解:

  • Lua C API和LuaJIT的FFI不混合。 FFI对象没有C API函数;我不确定你是怎么过来的。
  • LuaJIT是一个跟踪编译器,而不是一次编译方法。 loadstring等。将源代码解析为字节码(这仍然是一种改进),而不是机器代码,它只在LuaJIT确定它会提供主要性能提升的地方(通常是内部循环)发出。