[英]Calling a Lua function from LuaJ
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? 我可以从Lua调用Java函数,但是如何完成相反的操作呢? How do I call a Lua function from Java using LuaJ?
如何使用LuaJ从Java调用Lua函数?
I was looking around to solve this same problem and I came up with something very similar to Profetylen's answer 我正在四处寻找解决同样的问题,我想出了一些与Profetylen的答案非常相似的东西
test.java: 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: test.lua:
function MyAdd( num1, num2 )
return num1 + num2
end
快速浏览一下LuaJ文档 ,在我看来,你必须获得org.luaj.vm2.LuaFunction
对象,表示Lua函数,然后在其上应用invoke
方法。
I don't know, maybe this is what you want to do: (This will get you the return values inside Scala) 我不知道,也许这就是你想要做的事情:(这将获得Scala内部的返回值)
Main.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: 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). 编辑:当谷歌搜索时,我没有意识到这个问题与Scala无关(当我到达这里时,我本人正在寻找解决Scala中的问题)。 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!
然而,demon_ds1似乎已经根据我的回答在Java中找到了解决方案,现在他给出了自己的答案,所以我很高兴从这个令人困惑的答案中得到了好处!
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.
无论如何从java调用Lua代码非常简单,因为你总是可以通过像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/SampleJseMain.java
https://github.com/sylvanaar/luaj/blob/master/luaj-vm/examples/jse/ScriptEngineSample.java https://github.com/sylvanaar/luaj/blob/master/luaj-vm/examples/jse/ScriptEngineSample.java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.