简体   繁体   English

正确使用 lua 表/类

[英]Proper usage of lua tables/classes

I'm trying to use class behavior in lua where there is a ship that has two other classes pos and vector But I cannot get it working like I assumed I would be able to我正在尝试在 lua 中使用 class 行为,其中有一艘船有两个其他类 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

If anyone knows how to make the above code cleaner/better I would be thankful如果有人知道如何使上述代码更干净/更好,我将不胜感激

You can use metatables to set default fields.您可以使用元表来设置默认字段。 (I've made some assumptions about what you're trying to do. If this doesn't work for you, please add some clarification to your question.) (我对您尝试做的事情做了一些假设。如果这对您不起作用,请对您的问题进行一些说明。)

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

I found solution to do this, it still not perfect but only I got working was this modified code:我找到了解决方案,它仍然不完美,但只有我开始工作的是这个修改过的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM