Object-Oriented Programming: Difference between revisions
From Legacy Roblox Wiki
Jump to navigationJump to search
no edit summary
>NXTBoy (Removed redundant headings) |
>NXTBoy No edit summary |
||
Line 85: | Line 85: | ||
Now our objects have an identity, a state, and operations over this state. | Now our objects have an identity, a state, and operations over this state. | ||
== Constructors == | |||
So far, we've shown how to create a single once-use object. However, we might want to manage multiple accounts. Here's how we do it: | |||
<code lua> | |||
Account = {} | |||
function Account.new(balance) | |||
return setmetatable({balance = balance}, Account}) | |||
end | |||
Account.__index = Account | |||
</code> | |||
This creates the constructor {{`|Account.new(balance)}}, which returns a new account object. The {{`|setmetatable}} makes it so the new account will look in the {{`|Account}} table for its metamethods, and the metamethod {{`|Account.__index = Account}} makes it look in the {{`|Account}} table for its methods. Let's add some methods then! | |||
<code lua> | |||
function Account:withdraw(v) | |||
self.balance = self.balance - v | |||
end | |||
function Account:deposit(v) | |||
self.balance = self.balance + v | |||
end | |||
function Account:__tostring() | |||
return "Account(" .. self.balance .. ")" | |||
end | |||
</code> | |||
To use it: | |||
{{code and output|code= | |||
local a = Account.new(100) | |||
local b = Account.new(200) | |||
print(a, b) | |||
a:withdraw(20) | |||
b:deposit(40) | |||
print(a, b) | |||
|output= | |||
Account(100) Account(200) | |||
Account(80) Account(240) | |||
}} | |||
== See also == | == See also == |