Emulating javascript `this` behavior in lua

I always liked that in Javascript you can set the value of this pointer by running f.call(newThisPtrValue) . I wrote something for this in lua that works:

 _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 

There are a few things I'm not sure about:

  • I expect unpack({...}) performance overhead unpack({...}) . Is there any way around this?
  • Perhaps this will terribly disrupt the function environment?
  • Is this a really bad idea?
+4
source share
1 answer

One of the great benefits of Loo pseudo-OOP is that

 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" 

I wrote an article discussing this (among other things):
Lua Training: Syntax and the Pseudo-OOP Domain .

Change The following example is shown here, for example 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" 
+6
source

All Articles