I’ve always liked the way that in Javascript, you can set the value of the this pointer by doing f.call(newThisPtrValue). I wrote something to do this in lua, which 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 couple of things I’m unsure about:
- I expect there’s a performance overhead for
unpack({...}). Is there a way around this? - Is this likely to horribly break the environment of the function in any way?
- Is this a Really Bad Idea™?
One of the excellent benefits of Lua’s pseudo-OOP is that it’s super easy to do this already:
I have written an article that discusses this (among other things):
Learning Lua: Pseudo-OOP Syntax and Scope.
Edit: Here’s a continuing example like jQuery’s
each: