javalualuajava

Call a Java-method with a variable number arguments from a Luafile with LuaJava


in our project I try to call a java method from lua which has a variable number of arguments. So the code of the java-method looks like:

public static void addEvent( String luaFile, String function, 
                             int milliseconds, Object...args )
{
    events.add( new TimerEvent( luaFile, function, milliseconds, args ) );
}

I want to call this method from a lua file with the line:

mgr:addEvent( "luaFile.lua", "doSomething", 3000, var )

But using Luajava I allways get an error:

PANIC: unprotected error in call to Lua API (Invalid method call. No such method.)

Even removing the "var"-argument or adding some more arguments does not work.

So maybe anyone of you has ever used a java-method with variable arguments in a Lua-file and can give me a hint how I can solve this problem. I just don't want to use too many lines of code in the Lua-file as I would need for creating an ArrayList and adding arguments and passing this ArrayList to the Java-method. So maybe there is also a simple way to create an Array which I can pass as Array to Java. So a solution must not necessarily use vargs, but I thought it would be an easy way.

Thanks for any help in advance


Solution

  • Unfortunately, Java arrays are not currently supported by LuaJava. It does not allow the construction of new Java arrays and does not support operations with arrays (getting and setting values). Therefore it is unable suport the Object... args syntax.

    You could work around this by using specialized methods which take 0, 1, 2, 3 arguments (I do not think you would need more than 3). Then you would add a Lua vararg function which calls the appropriate function. An example for 3-argument call:

    public static void addEvent3( String luaFile, String function, 
                                 int milliseconds, Object arg1, Object arg2, Object arg3 )
    {
        events.add(new TimerEvent(luaFile, function, milliseconds, new Object[] {arg1, arg2, arg3}));
    }