Ejemplo n.º 1
0
func main() {
	// Create a new Lua VM
	L := lua.NewState()
	defer L.Close()

	// Register the Quat class and the methods that belongs with it.
	mt := L.NewTypeMetatable(lQuatClass)
	mt.RawSetH(lua.LString("__index"), mt)
	L.SetFuncs(mt, quatMethods)

	// The Lua constructor for new Quat objects. Takes four numbers.
	L.SetGlobal("Quat", L.NewFunction(func(L *lua.LState) int {

		// Get the four numeric values
		x := float64(L.ToNumber(1)) // argument 1
		y := float64(L.ToNumber(2)) // argument 2
		z := float64(L.ToNumber(3)) // argument 3
		w := float64(L.ToNumber(4)) // argument 4

		// Construct a new Quat
		userdata, err := constructQuat(L, unum.NewQuat(x, y, z, w))
		if err != nil {
			fmt.Println("ERROR", err)
			L.Push(lua.LString(err.Error()))
			return 1 // Number of returned values
		}

		// Construct a Lua table with the four values
		table := L.NewTable()
		table.Append(lua.LNumber(x))
		table.Append(lua.LNumber(y))
		table.Append(lua.LNumber(z))
		table.Append(lua.LNumber(w))

		// Set object fields that are not methods, but values
		mt := L.GetMetatable(userdata)
		L.SetField(mt, "x", lua.LNumber(x))
		L.SetField(mt, "y", lua.LNumber(y))
		L.SetField(mt, "z", lua.LNumber(z))
		L.SetField(mt, "w", lua.LNumber(w))
		L.SetField(mt, "table", table)
		L.SetMetatable(userdata, mt)

		// Return the Lua Quat object
		L.Push(userdata)
		return 1 // number of results
	}))

	// Run the Lua script
	if err := L.DoFile(luaFilename); err != nil {
		panic(err)
	}
}
Ejemplo n.º 2
0
// Method for adding quaternions in Lua
func quatAdd(L *lua.LState) int {
	self := checkQuat(L, 1)  // arg 1 (the object)
	other := checkQuat(L, 2) // arg 2 (first method argument)
	// Add self with other and return the result
	result := unum.NewQuat(self.X+other.X, self.Y+other.Y, self.Z+other.Z, self.W+other.W)
	userdata, err := constructQuat(L, result)
	if err != nil {
		fmt.Println(err)
		L.Push(lua.LString(err.Error()))
		return 1 // Number of returned values
	}
	L.Push(userdata)
	return 1 // Number of returned values
}