lua-users home
lua-l archive

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


I've got a base class "sprite" implemented in C, a subclass "ball" defined in Lua, and an instance of the subclass. I want to synthesize properties on the base class using __index and __newindex so that they're available to all instances. What I'm seeing, though, is that the "ball" table gets passed into sprite's __index function, not the instance. Here's a Lua example that shows the same behavior:

	a = { name = 'a' }
	print('a = '..tostring(a))
	a.__index = a

	function a.__index(self, key)
		print('a.__index('..tostring(self)..', '..key..')')
	
		if key == 'myname' then
			return self.name
		end
	
		if self ~= a then
			return a[key]
		else
			return nil
		end
	end

	b = { name = 'b' }
	print('b = '..tostring(b))
	b.__index = b
	setmetatable(b, a)
	print(b.myname)

	c = { name = 'c' }
	print('c = '..tostring(c))
	setmetatable(c, b)
	print(c.myname) -- prints 'b', not 'c'


Am I doing it wrong? Or is Lua's crazy OO hack not capable of this?

Thanks!
-Dave