lua-users home
lua-l archive

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


On Friday 15 September 2006 11:51 pm, Don Hopkins wrote:
> One question I have about Lua OOP in general is: why (in the examples on
> the Wiki) is there both a metatable, and also a separate method table
> (which the metatable points to with its __index attribute)? This seems
> kind of wastefully JavaScripty, and not as minimally Selfish as I'd
> expect. Is there any reason not to put methods and class variables
> directly into the metatable, and dispense with the extra method table in
> the metatable's __index attribute?

the metatable is not a "if not found search here" attribute, it's a table with 
well-defined slots to define several special behaviours.  one of them is 
creating table-like access for other objects (or extending it for real 
tables).  that is the __index slot. it can be a function or a table.  if it's 
a table, then its easy to use as an inheritance mechanism; but this is 
_only_one_ use case.  there are other ways to use metatables for other 
things.

if you want, you can set __index to point to the metatable itself.  you 
wouldn't be the first to prefer this setup:

mt={}
mt.__index=mt
setmetatable (obj, mt)

personally, i usually set two tables, one is the metatable, and the other is 
the methods table.   that is, when i bother to use OOP.  my typical factory 
function is something like this:

function newthing ()
	return setmetatable ({}, {__index = {
		meth1 = function (params)
			<code>
		end,
		meth2 = function (params)
			<code>
		end,
	}})
end

note that this creates a new metatable and methods table for each object, so 
it's only OK if you create a few very-long-lived instances

more frequent is the library-like class:

local thing_mths={}
local thing_mt={__index=thing_mths}

function thing_mths:method1 (params..)
	<code>
end

function thing_mths:method2 (params..)
	<code>
end

function newthing ()
	return setmetatable ({}, thing_mt)
end

(note that you could replace the first two lines to put the methods in the 
metatable)

of course, none of these handle inheritance.  so far i haven't missed it.  
after 15 years of C++ i've found that most simple problems don't need it, and 
most complex problems should use only a bit...  the biggest exception seems 
to be GUIs, still haven't find anything better than a big C++ framework for 
that

of course, if you want a generic tool to bind Lua with C++, you'll have to 
handle inheritance, i just wanted to show some usual idioms from the Lua side 
of things

-- 
Javier

Attachment: pgpiOfozgitjX.pgp
Description: PGP signature