正确使用lua表/类

时间:2019-09-21 10:55:56

标签: class 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}} -- I thought this would be sufficient for access being available for vector
}

-- create new ship class
function Ship:new(pos)
  p = p or {}
  p.pos = pos
  p.vector = Point:new{x=0,y=0} -- I need to do this or accessing vector will crash (The problem)
  return p
end

-- Create new ship...
plrShip = Ship:new{}
plrShip.pos.x = 300
plrShip.pos.y = 300

如果有人知道如何使以上代码更清晰/更好,我将很感激

2 个答案:

答案 0 :(得分:0)

您可以使用元表来设置默认字段。 (我对您要做什么做了一些假设。如果这对您不起作用,请为您的问题添加一些说明。)

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

-- create new ship class
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

-- Create new ship...
local plrShip = Ship:new{}
plrShip.pos.x = 300
plrShip.pos.y = 300

答案 1 :(得分:-1)

我找到了解决方案,但这仍然不完美,但只有我能做的是修改后的代码:

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