Inheritance Lua对象不是唯一的

Inheritance Lua对象不是唯一的,inheritance,lua,lua-table,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.

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

这是我的代码的简化:

--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

由于上次调用的是player:setimg,因此所有“对象”都以plyrimg结尾,因此它们不是唯一的

此函数在每次创建新对象实例时都在共享对象表上创建或覆盖属性

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
将查找索引链以查找
动画
,并将图像放置在共享属性中

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

如果不将self传递给构造函数,就可以避免很多问题。我通常这样定义类:

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文档中了解更多信息。

该死,我真的不明白,那么在构造函数中初始化表是没有意义的吗?这不是没有意义的!你只需要注意你在“构造函数”中分配给哪个表——记住在
new
中,
self
引用类而不是实例,当调用为
Player:new
Object:new
时。aaaaaaaaaaaaahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh