[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Functional objects
- From: Fabio Mascarenhas <fabiomasc@...>
- Date: Thu, 23 Sep 2004 13:43:25 -0300
Mark Hamburg wrote:
One loses direct read/write access to attributes, but closure-based (which
is probably a better term than functional now that I think about it) can
certainly have data as closure values. In fact, this data is more private
and accessed more efficiently since it doesn't involve a table lookup.
Table-based objects can also have private data that is efficiently accessed:
function makeObject()
local attribute = 1
local obj = {}
obj.attribute = function (self)
return attribute
end
obj.setAttribute = function (self, value)
attribute = value
end
obj.method = function(self,...)
...
end
return obj
end
Lacking a switch statement, however, method dispatch itself is slower.
You use a table to dispatch the call. :-)
function makeObject()
local attribute = 1
local methods = {}
methods.attribute = function ()
return attribute
end
methods.setAttribute = function (param)
attribute = param
end
methods.method = function(param)
-- method code goes here
end
return function( msg, param )
local method = methods[msg]
if method then
return method(param)
else
error( "Unknown message: " .. tostring( msg ) )
end
end
end
If you need more than one method then just use tables, don't try to
shoehorn closures into acting like them. If you absolutely need to
protect the methods (make sure some code does not change them) use a
proxy table, and run the code in a sandbox that does not have
getmetatable or setmetatable.
--
Fabio Mascarenhas