【发布时间】:2014-01-27 15:43:43
【问题描述】:
我的大部分编程都是在 Python 中完成的,并且我在我的大部分项目中都使用 OOP 实践。我最近开始研究 Love2D 游戏库和引擎。我设法配置了一些东西,然后考虑制作一个 GameObject 类。但是,这是什么? Lua 没有课程!它有表、元表和其他类似的东西。即使在多次阅读文档之后,我也很难确定这一点。
考虑以下示例:
catClass = {}
catClass.__index = catClass
catClass.type = "Cat"
function catClass.create(name)
local obj = setmetatable({}, catClass)
obj.name = name
return obj
end
cat1 = catClass.create("Fluffy")
print(cat1.type)
cat2 = catClass.create("Meowth")
cat1.type = "Dog"
print(cat1.type)
print(cat2.type)
print(catClass.type)
这个的输出如下:
Cat
Dog
Cat
Cat
我不明白为什么将 cat1.type 更改为“Dog”不会导致 cat2 和 catClass 发生相同的变化。设置元表是否会创建表的副本?谷歌没有提供有用的结果(很少有好的 Lua 解释)。
【问题讨论】: