vector ={x,y,z,
new = function(x,y,z)
o = setmetatable({},self)
self.__tostring = tostring
o.x = x or 0
o.y = y or 0
o.z = z or 0
return o
end,
Add = function(v1,v2)
return new(v1.x+v2.x,v1.y+v2.y,v1.z+v2.z)
end,
Sub = function(v1,v2)
return new(v1.x-v2.x,v1.y-v2.y,v1.z-v2.z)
end,
Mul = function (v1,v2)--叉积公式
return new(v1.y*v2.z-v2.y*v1.z,v1.z*v2.x-v2.z*v1.z,v1.x*v2.y-v1.y*v2.x)
end,
length = function()
return math.sqrt(self.x*self.x+self.y*self.y+self.z*self.z)
end,
tostring = function()
return "{"..self.x..","..self.y..","..self.z.."}"
end,
}
local v1=vector:new(1,2,3)
print(v1)
自己写的lua,不过错了
应该是这里错了
new = function(x,y,z)
o = setmetatable({},self)
self.__tostring = tostring
o.x = x or 0
o.y = y or 0
o.z = z or 0
return o
end,
不知道怎样改才能运行,每次运行都说self是nil,怎样改,原因是什么,在线等回答。。谢谢
------解决方案--------------------------------------------------------
终于见到学lua的了
lua中你那样定义函数是没有self的,要在外面定义,而且用“:”定义,":"调用
她面向对象的方法是用":"操作符号
当使用":"调用函数的时候相当于把:左边的一个对象当作函数的第一个参数
所以你的函数是
vector ={x,y,z}
function vector:__tostring()
return "{"..self.x..","..self.y..","..self.z.."}"
end
function vector:new(x,y,z)
o = setmetatable({},self)
o.x = x or 0
o.y = y or 0
o.z = z or 0
return o
end
function vector:Add(v1,v2)
return new(v1.x+v2.x,v1.y+v2.y,v1.z+v2.z)
end
function vector:Sub(v1,v2)
return new(v1.x-v2.x,v1.y-v2.y,v1.z-v2.z)
end
function vector:Mul(v1,v2)--叉积公式
return new(v1.y*v2.z-v2.y*v1.z,v1.z*v2.x-v2.z*v1.z,v1.x*v2.y-v1.y*v2.x)
end
function vector:length()
return math.sqrt(self.x*self.x+self.y*self.y+self.z*self.z)
end
local v1=vector:new(1,2,3)
print(v1)