LuaJ 向量类

我正在尝试创建一个用于 LuaJ 的向量类。我的最终目标是让用户不必写太多 Lua 代码,而且该向量类大多数工作都在我的 Java 引擎上完成。

据我了解,我需要为我的 Java 向量类设置 Lua 表的元表吗?但我现在遇到的问题是,当我试图覆盖一些元表功能时,在我的 Lua 脚本中似乎没有任何影响。我现在正在尝试覆盖 + 运算符,以便可以将两个向量相加或通过常量将向量相加。

这是我现有的 Vector 类:

package math;

import org.luaj.vm2.*;
import org.luaj.vm2.lib.*;
import org.luaj.vm2.lib.jse.*;

public class Vector3Lua {
    public float X;
    public float Y;
    public float Z;

    public Vector3Lua unit;

    static {
        // 设置 Vector 类
        LuaValue vectorClass = CoerceJavaToLua.coerce(Vector3Lua.class);

        // 元表处理
        LuaTable t = new LuaTable();
        t.set("__add", new TwoArgFunction() {
            public LuaValue call(LuaValue x, LuaValue y) {
                System.out.println("TEST1: " + x);
                System.out.println("TEST2: " + y);
                return x;
            }
        });
        t.set("__index", t);
        vectorClass.setmetatable(t);

        // 将“Vector3”与我们的类绑定
        luaj.globals.set("Vector3", vectorClass);
    }

    public Vector3Lua() {
        // 空的
    }

    // Java 构造函数
    public Vector3Lua(float X, float Y, float Z) {
        this.X = X;
        this.Y = Y;
        this.Z = Z;

        this.unit = new Vector3Lua(); // TODO 让它自动计算

        System.out.println("HELLO");
    }

    // Lua 构造函数
    static public class New extends ThreeArgFunction {

        @Override
        public LuaValue call(LuaValue arg0, LuaValue arg1, LuaValue arg2) {
            return CoerceJavaToLua.coerce(new Vector3Lua(arg0.tofloat(), arg1.tofloat(), arg2.tofloat()));
        }
    }

    // Lua 函数 - 点积
    public float Dot(Vector3Lua other) {
        if ( other == null ) {
            return 0;
        }

        return X * other.X + Y * other.Y + Z * other.Z;
    }

    // Lua 函数 - 叉积
    public LuaValue Cross(Vector3Lua other) {
        Vector3Lua result = new Vector3Lua( Y * other.Z - Z * other.Y,
                Z * other.X - X * other.Z,
                X * other.Y - Y * other.X );
        return CoerceJavaToLua.coerce(result);
    }
}

这是使用它的 Lua 脚本:

local test1 = Vector3.new(2, 3, 4);
local test2 = Vector3.new(1, 2, 3);
print(test1);
print(test2);
print(test1+2);

最后一行会产生一个错误,因为它说我不能将一个用户数据和一个数字相加。但是,我在向量类中尝试让它仅打印正在添加的内容,并返回原始数据(进行测试)。因此,我认为我的问题是如何定义元表;在我的向量类中,这两个打印语句从未被调用。

点赞
用户8076767
用户8076767

print(test1+2); 应该改为 print(test1+test2);。你得到这个错误是因为 test1 是一个用户数据(基本上是一个表格的低层版本),而 2 是一个数字。

2018-08-05 11:24:26