Re: Uncommon OOP in Lua: right or wrong?
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: Uncommon OOP in Lua: right or wrong?
- From: Wesley Smith <wesley.hoke@...>
- Date: 2010年9月24日 16:21:37 -0700
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))