lua-users home
lua-l archive

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


On Tue, Sep 12, 2006 at 09:47:24AM -0400, Aaron Brown wrote:
> Leo Razoumov wrote:
> 
> >How can one easily find out the number of records stored
> >in a table?  I think that there should be a convenient
> >idiom for such a common task.

> As lhf pointed out, it's surprisingly uncommon (given what a
> basic idea it is).  Here's how to do it:
> 
> local Count = 0
> for _ in pairs(Tbl) do Count = Count + 1 end

You can add that function to table, and then set all the table functions
as methods for new tables:

-- new functions in`table' package
function table.size(t)
	local s = 0
	for _ in pairs(t) do
		s = s+1
	end
	return s
end

function table.append(t, v)
	table.insert(t,v)
	return v
end

-- tables constructed as
--    t = table{ ... }
-- will be setup to have functions in `table' available as methods
table.__index = table

setmetatable(table,
  {
	  __call = function(_, t) setmetatable(t, table) return t end
  }
)

-- example
t = table{ hi = 4, that = 6, 12, 13 }

print(   t:size() ) -- 4

t:append(9)

print(   t:size() ) -- 5