我正在尝试创建一个与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);
最后一行产生了一个错误,因为它说明我不能将一个userdata和一个数字相加。然而,在我的向量类中,我试图让它只打印正在添加的内容,并返回原始数据(用于测试)。所以我认为我的问题是如何定义我的metatable;在我的vector类中,这两个print从来没有被调用过。
发布于 2018-08-05 19:24:27
print(test1+2);应为print(test1+test2);。之所以会出现这个错误,是因为test1是一个用户数据(基本上是一个表的底层版本),而2是一个数字。
https://stackoverflow.com/questions/46816130
复制相似问题