简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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