1

I am trying to overwrite the .new() lua function(method?) with LuaJ. I tried to set a "new" key in the metatable for my table, but when calling .new() in lua it is ignored and runs the default java-backed function of creating the table as a java object.

If I rename the key to (for example) "new2", and create it with "table.new2()" it works no problem.

Was hoping anyone could help me out!

Code so far:

    LuaValue vectorClass = CoerceJavaToLua.coerce(Vector3Lua.class);
    luaj.globals.set("Vector3", vectorClass);

    LuaTable table = new LuaTable();
    table.set("new2", new ThreeArgFunction() {
        public LuaValue call(LuaValue x, LuaValue y, LuaValue z) {
            System.out.println("Created new Vector: " + x + ", " + y + ", " + z);
            return LuaValue.NIL;
        }
    });
    table.set("__index", table);

    vectorClass.setmetatable( table );

Lua tester:

    local test1 = Vector3.new(2, 3, 4);  --> Does not print test message
    local test2 = Vector3.new2(4, 4, 4); --> Does print test message

The reason behind doing this is so I can apply a metatable to each instance of "Vector3" created automatically, to hide internal functionality from the user.

orange451
  • 21
  • 4
  • Unfortunately I don't know enough about LuaJ to give you a good answer, but I can tell you that your current solution will not work because `__index` is actually called when an already non-existing key is accessed. In your case, because `vectorClass.new` already exists, `__index` will not be called upon executing the code `Vector3.new`. That aside, are you not able to say something like `vectorClass.set("new", --[[function here]])`? – NetherGranite Aug 05 '18 at 11:15
  • The solution was not not use CoerceJavaToLua(). To gain the functionality I needed, I had to create a Vector class that extended a LuaValue. From there I can set the metatable, and then create a .new() method. – orange451 Aug 09 '18 at 12:16

0 Answers0