A new, dirty and amazingly efficient way to call a Lua function from your native Android code

Hi there,

I found a very smart way to call a Lua function from a native Android code…

You just have to create a lua code on the fly that call your function, and run it!

Thanks to the official JNLua documentation I managed to make this, based on the SimpleLuaExtension sample:

  1. from your Lua code, prepare your function and call your native code, with the function name as a parameter :

    function onNative(param) print(“Get called with this param:”,param) end myTests.myCall(“onNative”)

  2. From your Java code, just get the function name from the stack, and create a caller Lua function on the fly:

    // Get the function name from the stack String functionName = luaState.checkString(1); String myValue = “test”; // Create the Lua code, calling the Lua function luaState.load(“function CallFunction_fromNative() “+functionName+”(”"+myValue+"") end", “=simple”); // Evaluate the chunk, thus defining the function luaState.call(0, 0); // No arguments, no returns // Prepare a function call luaState.getGlobal(“CallFunction_fromNative”); // Push the function on the stack // Call luaState.call(0, 0);

Done!!