我正在使用 Love2d 和 Lua,看看我的自定义 Lua“类”:
-- Tile.lua
local Tile = { img = nil, tileType = 0, x = 0, y = 0 }
function Tile:new (img, tileType, x, y)
o = {}
setmetatable(o, self)
self.__index = self
self.img = img or nil
self.tileType = tileType or 0
self.x = x or 0
self.y = y or 0
return o
end
function Tile:getX ()
return self.x
end
return Tile
Run Code Online (Sandbox Code Playgroud)
并使用该类:
-- main.lua
Tile = require("src/Tile")
function love.load()
myGrass = Tile:new(nil, 0, 0, 0)
print(myGrass:getX()) -- 0
otherGrass = Tile:new(nil, 0, 200, 200)
print(myGrass:getX()) -- 200
end
Run Code Online (Sandbox Code Playgroud)
所以,我创建了一个Tile
叫做myGrass
用x = 0
,那么我等创建Tile
称为otherGrass
与现在x = 200
的结果是:我的第一次Tile
,myGrass
,改变自己的x
属性从0到200,因此MyGrass
和otherGrass
是同一个对象(表)。
这有效:
function Tile:new(img, tileType, x, y)
local o = {}
setmetatable(o, {__index = self})
o.img = img or nil
o.tileType = tileType or 0
o.x = x or 0
o.y = y or 0
return o
end
Run Code Online (Sandbox Code Playgroud)
将新值分配给新表,而不是self
.