lua-users home
lua-l archive

Re: Uncommon OOP in Lua: right or wrong?

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


Here's yet another technique that uses dot syntax but doesn't have the
memory problems of closures. It's likely to be slightly slower, but
not by much.
-- simulate a closure with __call
local closure = {}
function closure:__call(...)
	return self.f(self.self, ...)
end
setmetatable(closure, closure)
-- class table
local M = {}
M.__index = function(t, k)
	closure.self = t
	closure.f = M[k]
	return closure
end
-- instance functions
function M:something(val)
	print("something", val)
	self.something_else()
	return "return val"
end
function M:something_else()
	print("something_else")
end
-- create an instance
local m = setmetatable({}, M)
-- call it
print(m.something("a value", 23))

AltStyle によって変換されたページ (->オリジナル) /