# LUA简明教程

#### 运行

`print("Hello World")`

```chenhao-air:lua chenhao\$ lua
Lua 5.2.2  Copyright (C) 1994-2013 Lua.org, PUC-Rio
> print("Hello, World")
Hello, World
> ```

`>lua  file.lua`

```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```

#### 语法

##### 注释
`-- 两个减号是行注释`

```--[[
这是块注释
这是块注释
--]]```
##### 变量

Lua的数字只有double型，64bits，你不必担心Lua处理浮点数会慢（除非大于100,000,000,000,000），或是会有精度问题。

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

```a = 'alo\n123"'
a = "alo\n123\""
a = '\97lo\10\04923"'
a = [[alo
123"]]```

C语言中的NULL在Lua中是nil，比如你访问一个没有声明过的变量，就是nil，比如下面的v的值就是nil

`v = UndefinedVariable`

```theGlobalVar = 50
local theLocalVar = "local variable"```

#### 控制语句

##### while循环
```sum = 0
num = 1
while num <= 100 do
sum = sum + num
num = num + 1
end
print("sum =",sum)```
##### if-else分支
```if age == 40 and sex =="Male" then
print("男人四十一枝花")
elseif age > 60 and sex ~="Female" then
print("old man without country!")
elseif age < 20 then
io.write("too young, too naive!\n")
else
end```

1）“～=”是不等于，而不是!=
3）字符串的拼接操作符“..”

##### for 循环
```sum = 0
for i = 1, 100 do
sum = sum + i
end```

```sum = 0
for i = 1, 100, 2 do
sum = sum + i
end```

```sum = 0
for i = 100, 1, -2 do
sum = sum + i
end```
##### until循环
```sum = 2
repeat
sum = sum ^ 2 --幂操作
print(sum)
until sum >1000```

#### 函数

Lua的函数和Javascript的很像

##### 递归
```function fib(n)
if n < 2 then return 1 end
return fib(n - 2) + fib(n - 1)
end```
##### 闭包

```function newCounter()
local i = 0
return function()     -- anonymous function
i = i + 1
return i
end
end

c1 = newCounter()
print(c1())  --> 1
print(c1())  --> 2```

```function myPower(x)
return function(y) return y^x end
end

power2 = myPower(2)
power3 = myPower(3)

print(power2(4)) --4的2次方
print(power3(5)) --5的3次方```
##### 函数的返回值

Go语言一样，可以一条语句上赋多个值，如：

`name, age, bGay = "haoel", 37, false, "haoel@hotmail.com"`

```function getUserInfo(id)
print(id)
return "haoel", 37, "haoel@hotmail.com", "https://coolshell.cn"
end

name, age, email, website, bGay = getUserInfo()```

##### 局部函数

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

#### Table

`haoel = {name="ChenHao", age=37, handsome=True}`

```haoel.website="https://coolshell.cn/"
local age = haoel.age
haoel.handsome = false
haoel.name=nil```

`t = {[20]=100, ['name']="ChenHao", [3.14]="PI"}`

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

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

`arr = {"string", 100, "haoel", function() print("coolshell.cn") end}`

```for i=1, #arr do
print(arr[i])
end```

```_G.globalVar
_G["globalVar"]```

```for k, v in pairs(t) do
print(k, v)
end```

#### MetaTable 和 MetaMethod

MetaTable和MetaMethod是Lua中的重要的语法，MetaTable主要是用来做一些类似于C++重载操作符式的功能。

```fraction_a = {numerator=2, denominator=3}
fraction_b = {numerator=4, denominator=7}```

```fraction_op={}
ret = {}
ret.numerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator
ret.denominator = f1.denominator * f2.denominator
return ret
end```

```setmetatable(fraction_a, fraction_op)
setmetatable(fraction_b, fraction_op)```

`fraction_s = fraction_a + fraction_b`

```__add(a, b)                     对应表达式 a + b
__sub(a, b)                     对应表达式 a - b
__mul(a, b)                     对应表达式 a * b
__div(a, b)                     对应表达式 a / b
__mod(a, b)                     对应表达式 a % b
__pow(a, b)                     对应表达式 a ^ b
__unm(a)                        对应表达式 -a
__concat(a, b)                  对应表达式 a .. b
__len(a)                        对应表达式 #a
__eq(a, b)                      对应表达式 a == b
__lt(a, b)                      对应表达式 a < b
__le(a, b)                      对应表达式 a <= b
__index(a, b)                   对应表达式 a.b
__newindex(a, b, c)             对应表达式 a.b = c
__call(a, ...)                  对应表达式 a(...)```

#### “面向对象”

`setmetatable(a, {__index = b})`

```Window_Prototype = {x=0, y=0, width=100, height=100}
MyWin = {title="Hello"}
setmetatable(MyWin, {__index = Window_Prototype})```

```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```

1）self 就是 Person，Person:new(p)，相当于Person.new(self, p)
2）new方法的self.__index = self 的意图是怕self被扩展后改写，所以，让其保持原样
3）setmetatable这个函数返回的是第一个参数的值。

```me = Person:new()
print(me:toString())

kf = Person:new{name="King's fucking", age=70, handsome=false}
print(kf:toString())```

```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```

#### 模块

`print("Hello, World!")`

1）require函数，载入同样的lua文件时，只有第一次的时候会去执行，后面的相同的都不执行了。
2）如果你要让每一次文件都会执行的话，你可以使用dofile(“hello”)函数

```local hello = loadfile("hello")
... ...
... ...
hello()```

```local HaosModel = {}

local function getname()
return "Hao Chen"
end

function HaosModel.Greeting()
print("Hello, My name is "..getname())
end

return HaosModel```

```local hao_model = require("mymod")
hao_model.Greeting()```

```local hao_model = (function ()
--mymod.lua文件的内容--
end)()```