• Advertisement
Sign in to follow this  

Objects in Lua a standard?

This topic is 4181 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

So, I had a nice little OO script in Lua that provides object facilities. I decided those capabilities weren't enough, so I tried expanding it, and I broke my whole game. First, working script & usage example in pseudo-Lua:
function class(BaseClass)
	NewClass = {}

	if type(BaseClass) == "table" then
		for i,v in pairs(BaseClass) do
			NewClass[i] = v
		end
	end
end

CTest = class()
function CTest:Create()
	return setmetatable(
		{exampleDefaultVar = "default"},
		{__index = CTest}
	)
end

CTestSubclass = class(CTest)
function CTest:Create()
	return setmetatable(
		{
			exampleDefaultVar = "default", --shouldn't need to redefine this!
			additionalDefaultVar = 1
		},
		{
			__index = CTestSubclass
		}
	)
end



I found that I had to define the default variables in the Create() function, and if I wanted to add variables to a subclass, I had to redefine the variables in the subclass' Create() function that it should inherit from a parent class. This duplicates code and introduces more opportunities for error. I sought to rectify that with my second attempt:
function class(BaseClass)
	local NewClass = {}

	if type(BaseClass) == "table" then
		NewClass.default = BaseClass.default
		setmetatable(NewClass, {__index = BaseClass})
		NewClass.base = BaseClass
	else
		NewClass.default = {}
	end

	function NewClass:Create()
		return setmetatable(
			self.default,
			{__index = NewClass}
		)
	end
end

CTestBase = class()
CTestBase.default.testVar = 1
baseInstance = CTestBase:Create()

CTestDerived = class(CTestBase)
CTestBase.default.derivedTestVar = 2
derivedInstance = CTestBase:Create

--derivedInstance should contain both testVar and derivedTestVar



Instead of copying the contents of a parent class (as I did in my first attempt), I just set the __index metamethod of the new class to that parent class. I was worried that the indexing operations would be too expensive, but my inheritence hierarchies are pretty flat. I use a "default instance" table to hold all the variables that need to be in a new instance of the class returned by NewClass:Create(). Unfortunately, my game's state machine simply breaks under this change and I don't understand why. The actual question: Is there a standard (or nearly standard, like Boost is for C++) script for this kind of thing that I can just require() as I was doing with my own script? Failing that, what am I doing wrong in my second script? Thanks for any help you can offer, Me [Edited by - templewulf on August 11, 2006 10:07:05 AM]

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement