InLUAHow to callJAVA methodIs the content to be introduced in this article, mainly to learnLUACallingJAVA method, In useLuajavaIn open-source projects, how can we call java methods in lua and pass java objects as parameters to lua functions. The following is an example:
Create a loadScript class with the following code:
- public class LoadScript {
- LuaState L;
- LoadScript(final String filename){
- this.L = LuaStateFactory.newLuaState();
- this.L.openLibs();
- this.L.LdoFile(filename);
- }
- void closeScript(){
- this.L.close();
- }
- void runScriptFunction(String functionName,Object obj){
- this.L.getGlobal(functionName);
- this.L.pushJavaObject(obj);
- this.L.call(1,0);
- }
- }
Write a java object as follows:
- class LoadTest{
- String a;
- LoadScript script;
- public LoadTest(String script){
- this.script = new LoadScript(script+".lua");
- this.script.runScriptFunction("create",this);
- }
- public String getA() {
- return a;
- }
- public void setA(String a) {
- this.a = a;
- }
- }
The following is the test code:
- public static void main(String[] args) {
- LoadTest test = new loadTest("function");
- System.out.println(call.test.getA());
- }
In this way, we can pass the test object to the following lua code:
- function.lua:
- function create(M)
- M:setA("this is a")
- end
Summary: InLUAHow to callJAVA methodI hope this article will help you!