我试图了解这个功能的作用.任何人都可以向我解释这个吗? function newInstance (class) local o = {} setmetatable (o, class) class.__index = class return oend 它被称为这样: self = newInstance (self) 这个函数显
function newInstance (class)
local o = {}
setmetatable (o, class)
class.__index = class
return o
end
它被称为这样:
self = newInstance (self)这个函数显然可以在Lua中提供一个OOP变体(在我看来有点草率).
这是一个班级的工厂.
为清楚起见,可以重写如下:
C = { }
C.foo = function(self) -- just some method, so class would not be empty
print("foo method called", tostring(self))
end
C.__index = C -- (A)
function newInstance(class)
return setmetatable({ }, class) -- (B)
end
现在,如果我们创建两个新的C实例,我们清楚地看到它们都有一个方法foo(),但不同的自我:
o1 = newInstance(C) o1:foo() --> foo method called table: 0x7fb3ea408ce0 o2 = newInstance(C) o2:foo() --> foo method called table: 0x7fb3ea4072f0
foo方法是相同的:
print(o1.foo, o2.foo, o1.foo == o2.foo and "equal" or "different") --> function: 0x7fb3ea410760 function: 0x7fb3ea410760 equal
这是因为表C(“类”)是o1和o2的元表的__index(上面的(A)),在(B)中设置.但是o1和o2实际上是两个不同的表,在(B)创建(“类实例”或“对象”).
注意:我们在(A)处将C .__ index设置为等于C本身,因此我们将重用一个表.以下具有相同的效果:
prototype = { }
prototype.foo = function(self) -- just some method, so class would not be empty
print("foo method called", tostring(self))
end
C = { __index = prototype }
function newInstance(class)
return setmetatable({ }, class)
end
o = newInstance(C)
