Account = {balance=0, withdraw = function (self, v) self.balance = self.balance-v End } function Ac Count:deposit (v) self.balance = self.balance + v end account.deposit (account, 200.00) account : Withdraw (100.00)
Above This example, first, the account is a table, inside two elements, one is the key is balance, value is 0, one is a key is withdraw, value is a function.
Can be seen:
1. Functions can be defined in the table, this is like JS.
2. Self is the This within LUA
3. The method of calling the function is used.
4. If you want to omit self as a parameter, you can use the colon to define the function.
In addition, the following example shows that Lua is really oo:
Account = {balance = 0} function Account.withdraw (v) account.balance = account.balance-v End
A = account; Account = Nil a.withdraw (100.00) --error!
That is, when a variable points to another object, it is no longer possible to invoke the object's field on the original object, and the only way to do this is to use self, which is this, to point your field to your field, which sounds like something wrong.
function Account.withdraw (self, v) self.balance = self.balance-v End
Call again:
a1 = account; Account = nil ... A1.withdraw (A1, 100.00) --OK
It's OK.
There are OO inheritance, encapsulation, implementation interface, these are not my concern, after all, LUA implementation oo in my opinion is nonsense, I need it to deal with a bit of STR, the latter is not studied.
The object-oriented LUA