lua-users home
lua-l archive

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


Ignacio Castano wrote:
> 
> Hi,
> i don't know if that has been proposed before, but i
> think it would be usefull to have a tostring tag
> method, so that an object that is on the stack returns
> the result of the tm if it's defined, and in other
> case would return NULL. That would allow to print with
> ease info about userdata objects, or for example to
> fake constant strings using userdatas.

You can do this simply by replacing the tostring function.
To simplify it even further, also replace the settagmethod
and gettagmethod functions.  Here is some code that I've
been using to add arbitrary tag methods (e.g., tostring, 
type, and next).

It works with userdata just fine (I ran into the same 
problem which is why I did it -- although it was originally
for lua3.2).  The next tag method (along with a foreach
replacement) gave me the ability to traverse my C structures.

Hope it helps,

ajk

---- tagmethods.lua ----
_tagmethods = { 
--	next = _nextmethods, 
--	tostring = _tostringmethods,
--	type = _typemethods 
}

_settagmethod = settagmethod
function settagmethod (tag, method, f)
	local tm = _tagmethods[method]
	if tm then
		tm[tag] = f
	else
		%settagmethod(tag, method, f)
	end
end

function validtagmethods (new_only)
	local t 
	if new_only and new_only ~= 0 then
		t = {}
	else
		t = { "add", "sub", "mul", "div", "pow", "unm", 
				"lt", "gt", "le", "ge", 
				"concat", "index",
				"getglobal", "setglobal", "gettable", "settable",
				"function", "gc"
			}
	end
	if new_only ~= 0 then
		local i = next(_tagmethods, nil)
		while i do
			tinsert(t, i)
			i = next(_tagmethods, i)
		end
	end
	return t
end

_gettagmethod = gettagmethod
function gettagmethod (tag, method)
	local tm = _tagmethods[method]
	if tm then
		return tm[tag]
	else
		return %gettagmethod(tag, method)
	end
end

---- tostring.lua ----
_tostringmethods = {}
_tostring = tostring
function tostring (obj)
	local method = _tostringmethods[tag(obj)]
	if method then
		return method(obj)
	else
		return %tostring(obj)
	end
end

_tagmethods.tostring = _tostringmethods

-- 
Aaron Kamienski <aaronk@snaptwo.com>
SNAP2 Corporation