Reputation: 3057
So, I have a script that goes like so:
function testfunction()
print("Test from testfunction");
end
I am able to call Java functions from Lua, but how do I accomplish the opposite? How do I call a Lua function from Java using LuaJ?
Upvotes: 2
Views: 10987
Reputation: 958
I don't know, maybe this is what you want to do: (This will get you the return values inside Scala)
Main.scala:
import org.luaj.vm2._
import org.luaj.vm2.lib.jse._
object Main extends App {
val global = JsePlatform.standardGlobals()
global.get("dofile").call(LuaValue.valueOf("test.lua"))
val args: Array[LuaValue] = Array(LuaValue.valueof(1), LuaValue.valueof(2))
val retVals: LuaValue.Vararg = global.get("add").invoke(LuaValue.varargsOf(args))
println(retVals.arg(1))
}
test.lua:
function add(a, b)
a = a or 0
b = b or 0
return a + b
end
Note: I didn't test the code, but it think something like that should work.
edit: While googling around, I didn't realize this question had really nothing to do with Scala (I was myself looking to solve the problem in Scala when I got here). However, demon_ds1 seems to have found a solution in Java based on my answer and now he gave his own answer, so I'm glad something good came out of this confusing answer!
Upvotes: 2
Reputation: 164
I was looking around to solve this same problem and I came up with something very similar to Profetylen's answer
test.java:
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.JsePlatform;
public class test
{
public static void main(String[] args)
{
//run the lua script defining your function
LuaValue _G = JsePlatform.standardGlobals();
_G.get("dofile").call( LuaValue.valueOf("./test.lua"));
//call the function MyAdd with two parameters 5, and 5
LuaValue MyAdd = _G.get("MyAdd");
LuaValue retvals = MyAdd.call(LuaValue.valueOf(5), LuaValue.valueOf(5));
//print out the result from the lua function
System.out.println(retvals.tojstring(1));
}
}
test.lua:
function MyAdd( num1, num2 )
return num1 + num2
end
Upvotes: 12
Reputation: 8216
The examples are really helpful. It is very simple to call Lua code from java anyways, since you can always do it via something like loadstring.
https://github.com/sylvanaar/luaj/blob/master/luaj-vm/examples/jse/SampleJseMain.java
https://github.com/sylvanaar/luaj/blob/master/luaj-vm/examples/jse/ScriptEngineSample.java
Upvotes: 0