我有这个过滤器引擎,我想用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
我有两个问题:
答案 0 :(得分:2)
您可以使用loadstring
或luaL_loadstring
local filter = loadstring("local obj = ...; return obj.attribute")
local attr = filter(someobj)
-- Or:
luaL_loadstring(L, "local obj = ...; return obj.attribute")
虽然我应该澄清一些误解:
loadstring
等。将源代码解析为字节码(这仍然是一种改进),而不是机器代码,它只在LuaJIT确定它会提供主要性能提升的地方(通常是内部循环)发出。