[Lua] functions in Lua

Source: Internet
Author: User

The function in lua is a first-class function, which means that the lua function is not the same as that in C/C ++.

Local function print ()
-- Code here
End

-- Actually
Local print = function () -- anonymous function
-- Code here
End

Because the function is a first-class function, you can use a variable to index the function. In this case, the context information of the function also allows you to access external information in the function body. (This is a closure. If you are interested, go to the wiki)

This code is often seen:

Tb = {}
Function tb. print ()
End

In fact, with the above knowledge, we can also know that the Code just now is

Tb. print = function ()
End


In a table object such as tb, there is a print key, and the corresponding value is a function.

And: Call function parameter transfer:

The meaning of tb. print is slightly different from that of tb: print. Calling a function will pass in one more self, which is almost equivalent to calling a member function in OOP.
However, unlike the member function/non-member function in OOP, the non-member function in lua is called rather than static.
The tb object has a print function member. When tb is nil, you cannot call the print member... in OOP, this is not the case. Non-member functions are global.

PS: a previous company asked. the difference between member and non-member functions is actually a bit wrong. lua is a dynamic language, which is very different from C/CPP.

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.