[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: OO -> instance function environments
- From: "Wesley Smith" <wesley.hoke@...>
- Date: Tue, 27 Feb 2007 19:48:55 -0800
What is the most straightforward manner to have an instance of a class
work such that the self parameter of a function is implied
automatically by setting the environment of the function to the
instance?
Here's what I've come up with. I'd be very interested to hear about
other approaches.
Obj = {val = 0}
Obj_meta = {__index = _G}
function Obj.new()
local o = {}
setmetatable(o, Obj_meta)
for k, v in pairs(Obj) do
if(type(v) == "function" and k ~= "new") then
o[k] = function(...)
setfenv(v, o)
v(...)
end
else
o[k] = v
end
end
return o
end
function Obj:printVal()
print(val) --prints self.val
end
wes