A concise introductory tutorial on the Lua scripting language _lua

Source: Internet
Author: User
Tags lua

This is a systematic learning of the scripting language of Lua these days, and the Lua script is a lightweight script that is also known as the most performance-efficient script, used in many areas where performance is required, such as: Game scripts, Nginx,wireshark scripts, when you put down his source code and compile, You will find that the interpreter is less than 200k, how sick it is (/bin/sh have to 1m,macos platform), but also with the C language very good interaction. I'm curious to browse the LUA interpreter's source code, which is probably the cleanest C source I've ever seen.

I don't want to write a all-inclusive language handbook, on the one hand because there is already (see the link at the end of this article), the important reason is that because of the large length of the article will frustrate people's enthusiasm for learning, I always feel good article read up like a stool, can be very smooth to finish, To make people feel good (and that's why I don't want to write books). Therefore, this is bound to be a "into the toilet article", or that sentence, I hope this article can let everyone use commuting, toilet stool time to learn a technology. Oh.

I believe you are now in the toilet to take off your pants out of the buttocks are ready to defecate, then let us carefree excretion it ...

Run

First, we need to know that Lua is Class C, so he is sensitive to uppercase and lowercase characters.

Here's the LUA Hello World. Note: The semicolon of the statement for the Lua script is optional, and this is similar to the go language.

Copy Code code as follows:

Print ("Hello World")

You can execute a statement in a LUA shell, like Python, by running the LUA command on the command line.
Copy Code code as follows:

Chenhao-air:lua chenhao$ Lua
Lua 5.2.2 Copyright (C) 1994-2013 lua.org, Puc-rio
> Print ("Hello, World")
Hello, World
>

You can also save the script as a file and run it with the following command line.

Copy Code code as follows:

>lua File.lua

Or run like a shell:
Copy Code code as follows:

Chenhao-air:lua chenhao$ Cat Hello.lua
#!/usr/local/bin/lua
Print ("Hello, World")
Chenhao-air:lua chenhao$ chmod +x Hello.lua
Chenhao-air:test chenhao$./hello.lua
Hello, World

Grammar

Comments

Copy Code code as follows:

--two minus is a row comment

--[[
It's a block note.
It's a block note.
--]]

Variable

Lua's numbers are only double, 64bits, and you don't have to worry that Lua handles floating-point numbers slowly (unless greater than 100,000,000,000,000) or has a precision problem.

You can represent numbers in the following way, and the 16 at the beginning of 0x is very similar to C.

Copy Code code as follows:

num = 1024
num = 3.0
num = 3.1416
num = 314.16e-2
num = 0.31416E1
num = 0xFF
num = 0x56

Strings you can use single quotes, double quotes, and C-type escapes, such as: ' \a ' (bell), ' \b ' (backspace), ' \f ' (form), ' \ n ' (linefeed), ' \ R ' (enter), ' \ t ' (horizontal tabulation), ' \v ' (vertical tabulation), ' \ \ ' (backslash bar), ' \ ' (double quotes), and ' \ ' (single quotes)

The following four ways define exactly the same string (where two of the brackets can be used to define a string that has a newline)

Copy Code code as follows:

A = ' alo\n123 '
A = "alo\n123\" "
A = ' \97lo\10\04923 '
A = [[Alo
123 "]]

Null in C language is nil in Lua, for example, if you visit a variable that has not been declared, it is nil, for example, the value of V below is nil

Copy Code code as follows:

v = undefinedvariable

Boolean type only nil and false is false, number 0, ' empty string (' \0′ ' is true!

Also, be aware that the variables in LUA are all global variables without special instructions, even in statement blocks or functions. A local variable is a variable that is previously added to the Locals keyword.

Copy Code code as follows:

Theglobalvar = 50
Local Thelocalvar = ' local variable '

Control statements

No more, just look at the code (note: LUA has no + + or + + operations)

While loop

Copy Code code as follows:

sum = 0
num = 1
While Num <=
sum = sum + num
num = num + 1
End
Print ("sum =", sum)

If-else Branch

Copy Code code as follows:

if age = = and sex = "Male" Then
Print ("Men 41 Flowers")
ElseIf Age > Sex ~= "Female" Then
Print ("Old Mans without Country!")
ElseIf Age < Then
Io.write ("Too Young, too naive!\n")
Else
Local age = Io.read ()
Print ("Your age is" ...). Age
End

The above statement not only shows the If-else statement, but also shows the

1 "~=" is not equal to, not!=
2 Read and write functions read and write from stdin and stdout, respectively, of IO Library
3 string concatenation operator "..."

In addition, the or non-keyword in the conditional expression is: And, or, not.

For loop

Add from 1 to 100

Copy Code code as follows:

sum = 0
For i = 1
sum = sum + I
End

From 1 to 100 odd and

Copy Code code as follows:

sum = 0
For i = 1, 2 do
sum = sum + I
End

From 100 to 1 of even and

Copy Code code as follows:

sum = 0
For i = 1,-2 do
sum = sum + I
End

Until cycle

Copy Code code as follows:

sum = 2
Repeat
sum = sum ^ 2--Power operation
Print (sum)
Until Sum >1000

Function

The LUA functions are like JavaScript.

Recursion

Copy Code code as follows:

function fib (n)
If n < 2 then return 1 end
return fib (n-2) + fib (n-1)
End

Closed Bag

Again, JavaScript is possessed!

Example One

Copy Code code as follows:

function Newcounter ()
Local i = 0
return function ()--anonymous function
i = i + 1
return I
End
End

C1 = Newcounter ()
Print (C1 ())--> 1
Print (C1 ())--> 2

Example Two

Copy Code code as follows:

function Mypower (x)
return function (y) return y^x end
End

Power2 = Mypower (2)
Power3 = Mypower (3)

Print (Power2 (4))--4 2-Time Square
Print (Power3 (5))--5 3-Time Square

The return value of the function

As with the go language, you can assign multiple values to a single statement, such as:

Copy Code code as follows:

Name, age, Bgay = "Haoel", Panax Notoginseng, False, "haoel@hotmail.com"

In the code above, because there are only 3 variables, the fourth value is discarded.

Functions can also return multiple values:

Copy Code code as follows:

function GetUserInfo (ID)
Print (ID)
Return "Haoel", Panax Notoginseng, "haoel@hotmail.com", "Http://jb51.net"
End

Name, age, email, website, bgay = GetUserInfo ()

Note: In the above example, because there is no pass ID, the ID output in the function is nil, because the Bgay is not returned, so Bgay is also nil.

Local functions

The front of the function plus the local function, in fact, the function in Lua and a virtue in JavaScript.

For example: The following two functions are the same:

Copy Code code as follows:

function foo (x) return x^2 end
Foo = function (x) return x^2 end

Table

A table is actually a data structure of key value, much like the object in JavaScript, or an array in PHP, called dict or map,table in other languages:

Copy Code code as follows:

Haoel = {name= "Chenhao", age=37, Handsome=true}

The following is the CRUD operation for table:

Copy Code code as follows:

Haoel.website= "http://jb51.net/"
Local age = Haoel.age
Haoel.handsome = False
Haoel.name=nil

The top looks like a C + + structure, but name,age, handsome, website are key. You can also write a semantic table as follows:

Copy Code code as follows:

t = {[20]=100, [' Name ']= ' Chenhao ', [3.14]= ' PI '}

This is more like key value. So you can access: t[20],t["name", t[3.14].

Let's take another look at the array:

Copy Code code as follows:

arr = {10,20,30,40,50}

This looks like an array. But in fact it is equivalent to:
Copy Code code as follows:

arr = {[1]=10, [2]=20, [3]=30, [4]=40, [5]=50}

So, you can also define different types of arrays, such as:

Copy Code code as follows:

Arr = {"string", "M", "Haoel", Function () print ("coolshell.cn") End}

Note: The function can be invoked like this: Arr[4] ().

We can see that the Lua subscript didn't start at 0, starting at 1.

Copy Code code as follows:

For I=1, #arr do
Print (Arr[i])
End

Note: In the above procedure: #arr的意思就是arr的长度.

Note: Previously, the variables in Lua, if they have no local keywords, are all global variables, and LUA manages global variables with a table, LUA puts these global variables in a table called "_g."

We can access a global variable in the following way (assuming we have this global variable named Globalvar):

Copy Code code as follows:

_g.globalvar
_g["Globalvar"]

We can iterate through a table in the following way.

Copy Code code as follows:

For K, v. in pairs (t) do
Print (k, v)
End

MetaTable and Metamethod

MetaTable and Metamethod are important syntaxes in Lua, and metatable are mainly used to do something similar to the C + + overload operator.

For example, we have two points:

Copy Code code as follows:

Fraction_a = {numerator=2, denominator=3}
Fraction_b = {numerator=4, denominator=7}

We want to achieve the addition of points: 2/3 + 4/7, if we want to execute: fraction_a + Fraction_b, will be the error.

So, we can use MetaTable as follows:

Copy Code code as follows:

fraction_op={}
function Fraction_op.__add (f1, F2)
ret = {}
Ret.numerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator
Ret.denominator = F1.denominator * F2.denominator
return ret
End

Set metatable for the two table previously defined: (where setmetatble is a library function)

Copy Code code as follows:

Setmetatable (fraction_a, Fraction_op)
Setmetatable (Fraction_b, Fraction_op)

So you can do this: (Call the Fraction_op.__add () function)

Copy Code code as follows:

fraction_s = fraction_a + Fraction_b

As for __add This is Metamethod, this is the LUA built-in Convention, and the others are as follows Metamethod:
Copy Code code as follows:

__add (A, b) corresponding expression A + b
__sub (A, B) corresponds to an expression a-b
__mul (A, b) corresponding expression A * b
__div (A, B) corresponds to the expression b/a
__mod (A, b) corresponding to expression a% B
__pow (A, b) corresponding expression a ^ b
__UNM (a) corresponding expression-a
__concat (A, B) corresponds to the expression A. B
__len (a) corresponds to an expression #a
__eq (A, b) corresponding expression A = = B
__lt (A, b) corresponding expression a < b
__le (A, b) corresponding expression a <= b
__index (A, B) corresponds to an expression a.b
__newindex (A, B, c) corresponds to an expression a.b = C
__call (A, ...) corresponding expression A (...)

"Object Oriented"

Above we see has __index this overload, this thing mainly is overloads the Find key operation. This allows LUA to become a bit object-oriented, making it a bit like JavaScript prototype.

The so-called __index, make it clear that if we have two objects A and B, we want B as a prototype only need:

Copy Code code as follows:

Setmetatable (A, {__index = b})

For example, the following example: You can use a window_prototype template plus __index Metamethod to create another instance:
Copy Code code as follows:

Window_prototype = {x=0, y=0, width=100, height=100}
Mywin = {title= "Hello"}
Setmetatable (Mywin, {__index = Window_prototype})

So: Mywin can access x, y, width, height of dongdong. (Note: When a table is indexed to a value such as Table[key], LUA first finds the value of the key in the table itself, and if not, and if there is a metatable with a __index attribute on the list, Lua follows __ function logical lookup as defined by index)

With the above foundation, we can talk about the so-called Lua object-oriented.

Copy Code code as follows:

person={}

function Person:new (p)
Local obj = P
if (obj = = nil) Then
obj = {name= "Chenhao", age=37, Handsome=true}
End
Self.__index = Self
return setmetatable (obj, self)
End

function person:tostring ()
Return self.name ... ":". Self.age ... ":". (Self.handsome and "handsome" or "ugly")
End

Above we can see that there is a new method and a method of ToString. which

1 Self is person,person:new (p), equivalent to Person.new (self, p)
2 The Self.__index of the new method = Self is intended to be afraid that self is extended to overwrite, so keep it as it is
3 Setmetatable This function returns the value of the first parameter.

So: We can call this:

Copy Code code as follows:

me = Person:new ()
Print (me:tostring ())

KF = Person:new{name= "King ' s Fucking", age=70, Handsome=false}
Print (kf:tostring ())

as follows, I don't have to say that Lua is similar to JavaScript, and it's all changed over the prototype instance.

Copy Code code as follows:

Student = Person:new ()

function Student:new ()
NEWOBJ = {year = 2013}
Self.__index = Self
Return setmetatable (NEWOBJ, self)
End

function student:tostring ()
Return "Student:". Self.year ... ":". Self.name
End

Module

We can use require ("Model_name") to load other LUA files, the suffix of which is. Lua. The file is executed directly when loading. Like what:

We have a Hello.lua file:

Copy Code code as follows:

Print ("Hello, world!")

If we: Require ("Hello"), then directly output Hello, world! Out.

Attention:

1 require function, load the same LUA file, only the first time will be executed, the following the same do not execute.
2 If you want every file to be executed, you can use the Dofile ("Hello") function
3 If you want to play load and do not execute, when you need to execute, you can use the LoadFile () function, as follows:

Copy Code code as follows:

Local Hello = loadfile ("Hello")
... ...
... ...
Hello ()

LoadFile ("Hello"), the file does not execute, we assign the file to a variable hello, when hello (), the real execution. (We'd like JavaScript to have that kind of functionality, too.

Of course, the more standard gameplay is shown below.

Suppose we have a file called Mymod.lua, which reads as follows:

FileName: Mymod.lua

Copy Code code as follows:

Local Haosmodel = {}

Local function GetName ()
Return "Hao Chen"
End

function haosmodel.greeting ()
Print ("Hello, my name is" ...). GetName ())
End

Return Haosmodel

So we can use this:

Copy Code code as follows:

Local Hao_model = require ("Mymod")
Hao_model. Greeting ()

In fact, the require do is as follows: (so you know why our module file is written like that)

Copy Code code as follows:

Local Hao_model = (function ()
The content of the--mymod.lua file--
End) ()

Reference

I guess you're about to wipe your butt, so if you still prefer Lua, here are a few online articles you can continue to learn:

manual.luaer.cn LUA Online Handbook
book.luaer.cn Lua online LUA Learning tutorial
Chinese translation of the LUA Reference manual for the LUA Reference manual (Yunfeng translation version)

For Lua's libraries, you can look at official documents: string, table, Math,io, OS.

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.