我一直很喜欢在Javascript中你可以通过f.call(newThisPtrValue)
来设置this指针的值。我在lua写了一些东西来做这件事,它有效:
_G.call = function(f, self, ...)
local env = getfenv(f)
setfenv(f, setmetatable({self = self}, {__index = env}))
local result = {f(...)}
setfenv(f, env)
return unpack(result)
end
我不确定有几件事情:
unpack({...})
会有性能开销。有办法解决这个问题吗?答案 0 :(得分:6)
Lua的伪OOP的一个优点是它已经非常容易实现:
local Person = {}
function Person:create( firstName, lastName )
local person = { firstName=firstName, lastName=lastName }
setmetatable(person,{__index=self})
return person
end
function Person:getFullName()
return self.firstName .. " " .. self.lastName
end
local me = Person:create( "Gavin", "Kistner" )
local you = Person:create( "Eric", "Someone" )
print( me:getFullName() )
--> "Gavin Kistner"
print( me.getFullName( you ) )
--> "Eric Someone"
我写过一篇文章,讨论这个问题(除其他外): Learning Lua: Pseudo-OOP Syntax and Scope
编辑:这是一个像jQuery each
这样的持续示例:
local Array = {}
function Array:new(...)
local a = {...}
setmetatable(a,{__index=self})
return a
end
function Array:each(callback)
for i=1,#self do
callback(self[i],i,self[i])
end
end
function Array:map(callback)
local result = Array:new()
for i=1,#self do
result[i] = callback(self[i],i,self[i])
end
return result
end
function Array:join(str)
return table.concat(self,str)
end
local people = Array:new( me, you )
people:each( function(self,i)
print(self:getFullName())
end )
--> "Gavin Kistner"
--> "Eric Someone"
print( people:map(Person.getFullName):join(":") )
--> "Gavin Kistner:Eric Someone"