The object-oriented LUA

Source: Internet
Author: User

    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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.