Call Java method with variable number arguments from Luafile with LuaJava

in our project i am trying to call a java method from lua that has a variable number of arguments. So the java method code looks like this:

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 using the line:

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

      

But using Luajava I always get the error:

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

      

Even removing the "var" argument or adding multiple arguments doesn't work.

So, maybe some of you have 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 a Lua file as I need to create an ArrayList and add arguments and pass that ArrayList to a Java method. So maybe there is also an easy way to create an array that I can pass as an Array to Java. So the solution doesn't have to use vargs, but I thought it would be an easy way.

Thanks for any help in advance

+3


source to share


2 answers


Unfortunately Java arrays are not currently supported by LuaJava. It does not allow creating new Java arrays and does not support array operations (getting and setting values). Therefore, it cannot support syntax Object... args

.

You can get around this by using specialized methods that take 0, 1, 2, 3 arguments (I don't think you need more than 3). Then you have to add a Lua vararg function that calls the corresponding function. An example for a call with three arguments:



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

      

+1


source


The varargs parameter (for example Object... args

) does indeed have a type Object[]

.

LUA is (possibly) not capable of recognizing varargs and dynamically creating an array, so try this:



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

      

+1


source







All Articles