Jump to content
Sign in to follow this  
tigerx2

Banco, começando OO

Recommended Posts

tigerx2    1
tigerx2

Account = { b = 0,
		balance = function() print(Account.	end,
		withdraw = function (self, v)	self.b = self.b - v	end,
		deposit = function (self, v)	self.b = self.b + v	end
}

 

Tô começando a estudar OO, mas como diz o Skyen, isso nem chega a ser.

BTW, eu achei massa aí coloquei aqui ahuahu

Share this post


Link to post
Share on other sites
Socket    0
Socket

Isso não é POO (OOP) mesmo não.

 

Aqui um exemplo:

 

Account = {b = 0, history = "",
balance = function(self) return self.b end,
deposit = function(self, n) return self + n end,
withdraw = function(self, n) return self + (-n) end
}

function Account.create(self)
return setmetatable({},
{
	__index = self,
	__add = function(self, n) self:log((n > 0) and 1 or 2, n) self.b = self.b + n return self end,
	__call = function(self) return self.b end
})
end

function Account.log(self, a, s)
local func = {"Added", "Removed"}
self.history = self.history .. string.format(func[a] .. " %s gold.\n", math.abs(s))
end

function Account.see(self)
print(self.history:match("(.-)\n$"))
end

a = Account:create()

a:deposit(2)
a:deposit(5)
a:withdraw(3)
a:see()

 

Output:

 

Added 2 gold.

Added 5 gold.

Removed 3 gold.

 

E sim, tem como fazer menor, so que eu queria mostra que metaevento não é só __index.

Edited by Socket

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

×