lua-users home
lua-l archive

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


Phil has asked  a question (see below) about how to make type(obj) respond
"list" if obj is a list.  I have had this problem many times when setting up
objects of various types and have come up with the following method.
I associate a metatable with an object and assign a new variable named
'type' to the object as follows:

obj = {}  -- only data structure for objects
setmetatable(obj,{type='list'}) -- plus any other attributes desired such as
__add, __mul, etc.

One now needs to modify type() to check for a metatable type as follows:

rawtype = type
type = function (x)
 local mt = getmetatable(x)
 return mt and mt.__type or rawtype(x)
end

With this change to type() and the use of a type variable in the metatable,
one can now use

type(obj)  and have it return 'list'.

I think this would be an excellent addition to the basic Lua language, but
it is easily implemented on top of the existing Lua.

John Hauser


> Another respondent has suggested via private email that I
> look at the lauxlib.h and lauxlib.c files for samples of
> how to do what I want, and has answered some specific
> questions.  One that he didn't answer is how to make
> type(obj) respond "list" if obj is a list.  Can anyone
> else answer that question?  That question has caused some
> problems with scheme's generative types, now answered by
> srfi-9.