Lua表/类的正确用法

我正在尝试在Lua中使用类的行为,其中有一个船只拥有两个其他的类pos和vector,但我不能像我原以为会做到的那样让它正常工作

Point = {x=0, y=0}
function Point:new(p)
  p = p or {}
  return p
end

Ship =
{
  pos = {Point:new{x=0,y=0}},
  vector = {Point:new{x=0,y=0}} -- 我以为这样就足够可以访问vector了
}

-- 创建新的ship类
function Ship:new(pos)
  p = p or {}
  p.pos = pos
  p.vector = Point:new{x=0,y=0} -- 我需要这样做,否则访问vector将会崩溃(问题所在)
  return p
end

-- 创建新的船只...
plrShip = Ship:new{}
plrShip.pos.x = 300
plrShip.pos.y = 300

如果有人知道如何使上面的代码更简洁/更好,我会非常感激

点赞
用户3574628
用户3574628

你可以使用元表来设置默认字段。(我做了一些关于你想要做什么的假设。如果这对你不起作用,请在你的问题中添加一些澄清。)

local Point = {x=0, y=0}
Point.__index = Point
function Point:new(p)
  p = p or {}
  setmetatable(p, self)
  return p
end

-- 创建新的飞船类
local Ship = {}
Ship.__index = Ship
function Ship:new(pos)
  setmetatable(pos, Point)
  local p = {pos = pos, vector = Point:new()}
  setmetatable(p, self)
  return p
end

-- 创建新的飞船...
local plrShip = Ship:new{}
plrShip.pos.x = 300
plrShip.pos.y = 300
2019-09-21 14:27:21
用户9949842
用户9949842

我找到了解决方案,虽然并不完美,但我尝试的修改后的代码是:

Ship =
{
  pos = Point:new{x=0,y=0},
  vector = Point:new{x=0,y=0}
}

function Ship:new()
  p = p or {}
  p.pos = self.pos
  p.vector = self.vector
  return p
end

plrShip = Ship:new()
plrShip.pos.x = 300
plrShip.pos.y = 300
2019-09-21 15:10:14