如何在调用对象上运行LuaJ函数(LuaJ正在创建新对象,如何避免它)。

我从LuaJ网站上制作了一个简单的示例。[LuaJ](http://www.luaj.org/luaj/3.0/README.html“LuaJ”) 我正在尝试在当前正在使用的对象上运行一个函数,但是luaJ正在创建一个新对象。

如何在当前对象上运行函数,而不是创建新对象。

考虑以下代码...

import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.TwoArgFunction;
import org.luaj.vm2.lib.ZeroArgFunction;
import org.luaj.vm2.lib.jse.JsePlatform;

public class luaTest extends TwoArgFunction {

    public luaTest() {}
    changeInt mytest=new changeInt();

    public LuaValue call(LuaValue modname, LuaValue env) {
        LuaValue library = tableOf();
        library.set( "countup", new countup(mytest) );
        env.set( "luaTest", library );
        return library;
    }

    void run() {
        Globals globals = JsePlatform.standardGlobals();
        mytest.setA(10); // Setting it 10 before calling the script
        LuaValue chunk = globals.loadfile("script.lua");

        chunk.call();

    }
    class countup extends ZeroArgFunction {
        changeInt mytest;
        public countup(changeInt a)
        {
            mytest=a;
        }
        public LuaValue call() {
            return LuaValue.valueOf(mytest.countup());
        }
    }

}

changeInt类只有一个变量...

public class changeInt {

    int a = 1;
    public int countup(){
        return a++;
    }
    public void setA(int x)
    {
        a=x;
    }

}

lua脚本很简单..

require 'luaTest'

print('count',luaTest.countup())
print('count',luaTest.countup())
print('count',luaTest.countup())

有没有什么解决办法..

点赞
用户2722001
用户2722001

是的,对于 Java 程序员来说这很简单(我很新手 Java).. 我使用了单例模式,问题得到了解决。

2015-06-23 06:24:48