我一直很喜欢在 Javascript中你可以通过f.call(newThisPtrValue)来设置this指针的值的方式.我在lua写了一些东西来做这件事,它起作用: _G.call = function(f, self, ...) local env = getfenv(f) setfenv(f, setmet
_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({…})有性能开销.有没有解决的办法?
>这有可能以任何方式严重破坏功能的环境吗?
>这是一个真的不好的想法吗?
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一样的持续例子:
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"