Page 2 of 2

Re: WeaverOOP - A budding OOP library

Posted: Wed Aug 03, 2011 6:57 pm
by Robin
LuaWeaver wrote:But how do the metatables work with this? That's what I need to know.
This: the __index metamethod.

The basis is simple:

Code: Select all

SomeClass = {}
function SomeClass:foo()
    print(self.name)
end

SomeInstance = {name = 'blah'}
setmetatable(SomeInstance, {__index = SomeClass})
SomeInstance:foo() -- prints blah
Pretty much every Lua OOP worth its salt boils down to this.

Re: WeaverOOP - A budding OOP library

Posted: Thu Aug 04, 2011 9:30 am
by Roland_Yonaba
LuaWeaver wrote:But how do the metatables work with this? That's what I need to know.
I'll strongly recommend PIL, especially chapter 13. You will find useful explanations there.

Re: WeaverOOP - A budding OOP library

Posted: Tue Aug 09, 2011 12:09 am
by LuaWeaver
I've been working on it, and this is what I have so far.

main.lua

Code: Select all

require "WeaverOOP"

enity=class:new()
enity.name="Enity"
enity.maxHp=100
enity.hp=100
enity.mana=1000
enity.damage=10
enity.defence=1
enity.accuracy=75

function enity.speak(enity2)
	print("Hi! I'm "..self.name.."! I have "..tostring(self.hp).." hp out of "..tostring(self.maxHp).." left! I also have "..tostring(self.mana).." left!")
end

function enity.damage(enity2, target)
	for i=1, self.accuracy do
		if math.random(1, 100)==15 then
			target.hp=self.damage-target.defence
		end
	end
end

character=object.new(enity)

character:speak()

character:damage(character)

character:speak()
WeaverOOP.lua

Code: Select all

class={}
class.__index=class
object={}
object.__index=class

function class:new()
	local class2={}
	class2.__index=class
	return class2
end

function object.new(class2)
	local object2=class2
	object2.__index=class2
	return object
end
And I get this error message:

Code: Select all

main.lua:26 attempt to call method 'speak' (a nil value)

What did I do wrong D:?

Re: WeaverOOP - A budding OOP library

Posted: Tue Aug 09, 2011 2:15 am
by LuaWeaver
Never mind, solved on a different forum.