lua-users home
lua-l archive

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


It was thus said that the Great Sam Pagenkopf once stated:
> local function setlength (t, len)
>   local mt = getmetatable(t) or {}
>   setmetatable(t,mt)
>   mt.__len = function () return len end
> end
> 
> ^ Sean, are you referring to this type of solution? I am sure it would
> cover some bases.

  No, I'm talking about existing code where #t becomes a left-hand side
value.  Code written to the current standard will only expect one parameter
to the __len metamethod, and swapping it out with that could break existing
code.

  Also, userdata can add behavior to the __len metamethod---what happens in
those cases?  You just can't assume that # only applies to tables.

  What should happen in the following cases?

	s = "some string"
	t = { "some table" }
	u = make_new_userdata()

	print(#s)
	print(#t)
	print(#u)

	#s = 10 assert(#s == 10)
	#t = 10 assert(#t == 10)
	#u = 10 assert(#u == 10)

	#s = 0 -- does this free the string?  Turn it into ""?
	#t = 0 -- does this mark all elements are garbage?
	#u = 0 

	t = { 1 , 2 , 3 , 4 , 5 }
	#t = 10 -- elements 6 through 10 are now nil, right?
	table.remove(t,1)   -- #t is now what?  What are the contents?
	table.remove(t)     -- what about now?
	table.insert(t,'x') -- and so on ...
	table.sort(t)	    -- this could be problematic as well

  -spc