Lua对象不是唯一的

时间:2016-10-13 00:04:54

标签: inheritance lua lua-table

在尝试创建一个非常简单的类继承时,所有对象似乎都在共享相同的值

这是我的代码的简化:

--Generic class
Object = {}

function Object:new (type,id,name)
  o = {}
  self.type = type or "none"
  self.id = id or 0
  self.name = name or "noname"
  self.direction = "down"
  self.animations = {}
  self.animations.stack = {}
  self.animations.idle = {}
  self.animations.idle[self.direction] = {}
  setmetatable(o, self)
  self.__index = self
  return o
end

function Object:draw(x,y)
  local img = self.animations.idle["down"][0]
  print("drawing " ..self.name.." as "..img)
end

function Object:setimg(img)
  self.animations.idle["down"][0] = img
end

Player = Object:new()

-- Player class
function Player:new(id,name)
  local o = self

  o.id = id or 0
  o.name = name or "noname"

  o.collision = {}
  o.collision.type = "player"

  return o
end

function Player:move(x,y)
  print("moving to ",x,y)
end

-- Testing
blockimg = "block.png"
grassimg = "grass.png"
plyrimg = "player.png"

block = Object:new("solid",1,"block")
block:setimg(blockimg)

grass = Object:new("floor",3,"grass")
grass:setimg(grassimg)

player = Player:new(1, "plyr1")
player:setimg(plyrimg)

block:draw() -- >drawing grass as player.png
grass:draw() -- >drawing grass as player.png
player:draw()-- >drawing plyr1 as player.png

由于玩家:setimg是最后一次调用,所有“对象”都以plyrimg结束,因此它们不是唯一的

2 个答案:

答案 0 :(得分:2)

每次创建新的Object实例时,此函数都会在共享Object表上创建或覆盖属性。

function Object:new (type,id,name)
  o = {}
  self.type = type or "none"
  self.id = id or 0
  self.name = name or "noname"
  self.direction = "down"
  self.animations = {}
  self.animations.stack = {}
  self.animations.idle = {}
  self.animations.idle[self.direction] = {}
  setmetatable(o, self)
  self.__index = self
  return o
end

如果您希望它们是唯一的,则需要在每个新实例上创建这些属性。否则,Object:setimg将查找索引链以查找animations,并将图像放在共享属性中。

function Object:new (type,id,name)
  local o = {}
  -- ...
  o.animations = {} -- Or in Player:new
  -- ...
  self.__index = self
  return setmetatable(o, self)
end

答案 1 :(得分:0)

如果您只是将自己传递给构造函数,则可以避免很多问题。我通常会定义这样的类:

local class={x=0,y=0}
local _class={__index=Class}
-- I like prefixing metatables with _, but that's just a personal thing
class.new(x, y)
  return setmetatable({x=x, y=y}, _class)
end
class:print() print(self.x, self.y) end
class.sub(sub) return getmetatable(sub)==_class end

这假设类要么在自己的文件中,要么在do块中,以保持局部变量对除了类及其闭包之外的任何内容隐藏。

您可以在github上的lua文档中阅读更多相关内容。