【发布时间】:2017-10-18 17:41:52
【问题描述】:
我正在尝试创建一个用于 LuaJ 的 Vector 类。最终目标是让用户不用写太多的 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 {
// Setup Vector class
LuaValue vectorClass = CoerceJavaToLua.coerce(Vector3Lua.class);
// Metatable stuff
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);
// Bind "Vector3" to our class
luaj.globals.set("Vector3", vectorClass);
}
public Vector3Lua() {
// Empty
}
// Java constructor
public Vector3Lua(float X, float Y, float Z) {
this.X = X;
this.Y = Y;
this.Z = Z;
this.unit = new Vector3Lua(); // TODO Make this automatically calculate
System.out.println("HELLO");
}
// Lua constructor
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 Function - Dot Product
public float Dot(Vector3Lua other) {
if ( other == null ) {
return 0;
}
return X * other.X + Y * other.Y + Z * other.Z;
}
// Lua Function - Cross Product
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);
最后一行产生错误,因为它说我不能将用户数据和数字相加。但是,在我的矢量类中,我试图让它只打印正在添加的内容,然后返回原始数据(以进行测试)。所以我相信我的问题是我如何定义我的元表;在我的矢量类中,这两个打印从未被调用过。
【问题讨论】:
-
我不知道 LuaJ 以及用例是什么,但
print(test1+2);对我来说似乎有点困惑。不是print(test1+test2);吗? -
在这种情况下是一个测试。将来可能会添加两个向量,但我还想实现一个由常量添加的向量。