LuaJ Vector Class

时间:2017-10-18 17:41:52

标签: java metatable luaj

我正在尝试创建一个与LuaJ一起使用的Vector类。最终目标是让用户不要写很多lua,并且在我的Java引擎上完成大部分工作。

根据我的理解,我需要为我的Java矢量类的lua表示设置metatable?我遇到的问题是,当我试图覆盖一些metatable功能时,它似乎对我的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和数字一起添加。但是,在我的vector类中,我试图让它只打印正在添加的内容,然后返回原始数据(进行测试)。所以我相信我的问题是我如何定义我的元数据;在我的vector类中,从不调用两个print。

1 个答案:

答案 0 :(得分:0)

print(test1+2);应该是print(test1+test2);。之所以出现该错误,是因为test1是一个用户数据(基本上是表的幕后版本),而2是一个数字。