lua-users home
lua-l archive

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


I was wondering...I am using using tables to model objects in a C++ like
manner. A table would have  attributes and methods, similar to a C++
class. If the program creates hundreds or thousands of these objects
each object would have its own instance of the same functions.

A = function(t) -- constructor A
	t.getName = function(self) return self.name end
	return t
end

list = {}
for i=1,1000 do
	tinsert(list, A{name=i})
end

In list I have 1000 A objects, each one has its own instance of
getName()

FUNC = function(self) return self.name end

A = function(t)
	t.getName = FUNC
	return t
}

Above each object's getName() is holding a reference to the function
FUNC. Only one instance of the function exists. This could potentially
save you plenty of memory.

I have to admit, this wasn't entirely clear to me at first. Just thought
other young budding Lua programmers could benefit from this.

-Lenny.