LuaJ how to run the function on the calling object ( LuaJ is making new object How Can it be avoided.)

332 views Asked by At

I have made a trival example from luaj website.. LuaJ I am trying to run a function on the current object which is currently being used. but luaJ is making a new object.

How can I run the function on the current object, not making a new one.

cosidering the following code...

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());
        }
    }

}

the changeInt class is simple one variable...

public class changeInt {

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

}

luaScript is simple..

require 'luaTest'

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

is there any way around it..

1

There are 1 answers

0
BravoAlphaRomeo On

Yeah it was very trival for java programmers (I am very new to java).. I used Singleton pattern and it solved the problem.