Ir para conteúdo
Entre para seguir isso  
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

Compartilhar este post


Link para o post
Compartilhar em outros 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.

Editado por Socket

Compartilhar este post


Link para o post
Compartilhar em outros sites
Visitante
Este tópico está impedido de receber novos posts.
Entre para seguir isso  

  • Quem Está Navegando   0 membros estão online

    Nenhum usuário registrado visualizando esta página.

×