javaluaj

Multiple return values in LuaJ


I've been trying to find a way to return multiple values from a Java method in LuaJ. That is, return multiple values from Java to be retrieved inside Lua code.

Once again... What I mean is:

public LuaValue call() {

    Dimension size = guiConsole.getSize();

    int width = LuaValue.valueOf(size.width), height = LuaValue.valueOf(size.height);

    return width, height; // This obviously wouldn't work, but this is the functionality I'm after

}

So that I then from Lua code can do:

width, height = getSize()

Successfully retrieving both the width and the height.

Best regards,


Solution

  • I managed to find out how to do it. After doing some more research, it turns out there's a VarArgFunction that you can extend your class by. Instead of then returning your LuaValue like you normally would in the "call()" method, you use the "invoke(Varargs v)" method. This allows you to return a Varargs object containing LuaValues. A Varargs is constructed using the "LuaValue.varargsOf(LuaValue[] luaValues)" method.

    Example:

    public class GetSize extends VarArgFunction {
    
    private Dimension size;
    
    public GetSize(Dimension size) {
    
        this.size= size;
    
    }
    
    public Varargs invoke(Varargs v) {
    
        Varargs varargs = LuaValue.varargsOf(new LuaValue[] {LuaValue.valueOf(size.width), 
                LuaValue.valueOf(size.height)});
    
        return varargs;
    
    }
    
    }
    

    That being said, it is now possible retrieving two values from the "getSize()" function in Lua!

    width, height = getSize()
    

    Yay!