lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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