lua-users home
lua-l archive

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


On 14/01/2010 19:14, Luiz Henrique de Figueiredo wrote:
__len is still able to return non number values. What is the position
about that? Is that the desired behaviour?

__len can return any Lua value:

for k,v in ipairs({true,print,"hello",{},io.stdin}) do
	a=setmetatable({},{__len=function() return v end})
	print(k,v,#a)
end

1	true	true
2	function: 0x9bbdfd0	function: 0x9bbdfd0
3	hello	hello
4	table: 0x9bc2240	table: 0x9bc2240
5	file (0x2e5420)	file (0x2e5420)



Well, as Mike pointed out, __add can return non number values and that is reasonable. For instance, a vector library so that v3 = v1 + v2 will benefit from __add being able to return anything. But I can't think of a case where the length of something is not a numeric value.

For me, __len has clear semantics. The length of something is measurable in 'n' units, with 'n' being a number.

Using __len for other uses seems like a case of operator overloading abuse (C++).

Even the common idiom of "t[#t + 1] = something" will have to take care of checking the type of #t before doing arithmetic with it.

And in a related note, if now there is lua_rawlen, shouldn't it have a non-raw version, like gettable / rawget, etc?

Regards,
Ignacio