简体   繁体   English

LuaJ导入Lua方法

[英]LuaJ Import Lua Methods

I'm using LuaJ, and I have a .lua file filled with a bunch of functions. 我正在使用LuaJ,并且我有一个.lua文件,其中包含许多函数。 How do I import these functions to use in Java with LuaJ? 如何导入这些功能以在Java与LuaJ中使用?

One option would be to compile the file into Java code and import that. 一种选择是将文件编译为Java代码并将其导入。 Another would be to simply invoke the Lua file directly from your Java code using the embeddable interpreter. 另一个方法是使用可嵌入解释器直接从Java代码直接调用Lua文件。


* EDIT * *编辑*

There are good examples in the downloaded documentation. 下载的文档中有很好的示例。 To run a script from within Java you would do something like this: 要从Java内部运行脚本,您需要执行以下操作:

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class LuaTest {
    public static void main(String[] args) throws Exception {
        String scriptFilePath = "/Users/developer/work/luaj-2.0.2/examples/lua/hello.lua";

        Reader reader = new FileReader(new File(scriptFilePath));
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine e = mgr.getEngineByExtension(".lua");
        Object result = e.eval(reader);
    }
}

To compile a Lua script into Java source code, you would do something like this: 要将Lua脚本编译为Java源代码,您需要执行以下操作:

java -cp lib/luaj-jse-2.0.2.jar lua2java -s examples/lua -d . hello.lua
javac -cp lib/luaj-jse-2.0.2.jar hello.java

These examples are pretty much taken from the README.html which you get when you download Luaj. 这些示例几乎取自下载Luaj时获得的README.html。 I would highly recommend reading it end to end to get a good grasp of the available functionality. 我强烈建议从头到尾阅读它,以更好地掌握可用功能。

I was looking around to solve this same problem myself and although this question was from January hopefully this post will help others looking for help. 我一直在四处寻找解决相同问题的方法,尽管这个问题来自一月份,但希望这篇文章能对其他人有所帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM