0

我正在尝试创建一个与 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); 

最后一行产生一个错误,因为它说我无法将用户数据和数字相加。但是,在我的矢量类中,我试图让它只打印正在添加的内容,然后只返回原始数据(以进行测试)。所以我相信我的问题是我如何定义我的元表;在我的矢量类中,从未调用过这两个打印。

4

1 回答 1

0

print(test1+2);应该是print(test1+test2);。你得到这个错误是因为test1它是一个用户数据(基本上是一个表的底层版本)并且2是一个数字。

于 2018-08-05T11:24:26.540 回答