Lua是一门动态解释型语言,其作为C\C++的绝好伴侣,其使用场景非常之多,在web场景中,常作为模块代码与nginx共同工作。

安装

Lua的官网教程。

  1. curl -R -O http://www.lua.org/ftp/lua-5.3.5.tar.gz
  2. tar zxf lua-5.3.5.tar.gz
  3. cd lua-5.3.5
  4. make linux test / make macosx test
  5. make linux install / make macosx install
  6. // 查看是否安装成功
  7. lua -v
  8. Lua 5.3.5 Copyright (C) 1994-2018 Lua.org, PUC-Rio
  9. // 进入repl
  10. lua

语法

作为一门动态类型的语言,Lua的语法与JavaScript非常相似,不同之处在于lua语法更加简单。Lua基础语法可参考菜鸟教程。

基本类型

  1. 数字:数字类型是64位的浮点数类型
  2. 布尔值
  3. 字符串:
  4. 空值:nil
  5. 函数:function
  6. table
  7. 协程
  8. userdata:表示任意存储在变量中的C数据结构

变量与作用域

Lua的变量默认是全局的,但是可以通过local关键字来声明局部作用域变量。

> a1 = 1      // 全局作用域
> local b1 = 2  // 局部作用域
>
> function scope(a, b)
>>    a2 = a * 2    // 全局作用域
>>  local b2 = b * 3    // 局部作用域
>        return a2 + b2
> end
>

控制流程

Lua内建的流程包含if语句、两种for循环,repeat循环以及while循环。

// if语句
if film == 'Raiders' then
    print('Good')
elseif film == 'Temple' then
    print('Ha~')
else
    print('Huh?')

// for循环
for i = 1, 5 do
    print(i)  // 1,2,3,4,5
end

for i = 1, 5, 2 do
    print(i)  // 1, 3, 5
end

//while循环
while(true) do
   print("循环将永远执行下去")
end

//repeat util循环
a = 10

repeat
   print("a的值为:", a)
   a = a + 1
until( a > 15 )

尾递归:Lua的函数都做了尾递归优化。

Table

与Python的字典(dictionary)和Ruby的哈希(hash)类似,Lua的table是键值对的集合。

book = {
  title= 'Grail',
  author = 'David',
  pages = 100
}

print(book.title)  // Grail

// 删除一个元素
book.pages = nil

// 遍历book
for k, v in pairs(book) do
  print(k .. '..' .. v)
end
// title..Grail
// author..David
// pages..100

// 数组的使用
medals = { 'gold', 'silver', 'bronze' }

medals[1] // gold 数组的索引是从1开始的

// 字典与数组公用
ice_cream_scoops = {
    'vanilla',
  'chocolate';

  sprinkles = true
}

ice_cream_scoops[1] // 'vanilla'
ice_craem_scoops.sprinkles // true

metatables

如果你想在找不到键所对应的值时不返回nil,而是返回其他的默认值;或者你想把读写的历史记录到某一个table,此时可以通过metatable来实现,metatable就相当于“自定义行为”。

local book = {
  title= 'Grail',
  author = 'David',
  pages = 100
}

print(book) // table: 0x7f8b064059f0

local function table_to_string(t)
  local result = {}

  for k, v in pairs(t) do
    result[#result+1] = k .. ":" .. v
  end

  return table.concat(result, "\n")
end

local mt = {
  __tostring = table_to_string
}

setmetatable(book, mt)

print(book)
// title:Grail
// pages:100
// author:David

面向对象

我们想要实现一个攻击Boss等级的反派,游戏引擎通过发送take_hit()的消息来响应对反派的攻击。

原型

Villain = {
  health = 100,

  new = function(self, name)
    local obj = {
      name = name,
      health = self.health
    }

        // 利用metatable来实现类型js中原型的作用,当前对象没有的话就去原型上找
        setmetatable(obj, self)
    self.__index = self

    return obj
  end,

  take_hit = function(self)
    self.health = self.health - 10
  end
}

local dietrich = Villain.new(Villain, 'Dietrich')

Villain.take_hit(dietrich)
dietrich.take_hit(dietrich)

print(dietrich.health) // 80

继承

此时创建一个超级大反派,只需要在原先的反派上更改就可以了。

SuperVillain = Villain.new(Villain)

function SuperVillain.take_hit(self)
  self.health = self.health - 5
end

local toht = SuperVillain.new(SuperVillain, 'Toht')
toht.take_hit(toht)

print(toht.health) // 95

语法糖

如果你写的是table:method()而不是table.method(self),lua会隐式的替你传入self这个参数。

local Villain = {
  health = 100
}

function Villain:new(name)
  local obj = {
    name = name,
    health = self.health
  }

  setmetatable(obj, self)
  self.__index = self

  return obj
end

function Villain:take_hit()
  self.health = self.health - 10
end

local dietrich = Villain:new('Dietrich')
dietrich:take_hit()

print(dietrich.health)

协程

Lua中的代码都是以串行的方式运行的。但是它又内建了一个用于处理多任务的基本类型:协程。

子程序就是协程的一种特例。 — Donald Knuth


从操作系统角度上来说,Process -> Thread -> Coroutine。协程(Coroutine)是编译器级的,进程(Process)和线程(Thread)是操作系统级的。

进程(Process)和线程(Thread)是os通过调度算法,保存当前的上下文,然后从上次暂停的地方再次开始计算,重新开始的地方不可预期,每次CPU计算的指令数量和代码跑过的CPU时间是相关的,跑到os分配的cpu时间到达后就会被os强制挂起,开发者无法精确的控制它们。

协程(Coroutine)是一种轻量级的用户态线程,实现的是非抢占式的调度,即由当前协程切换到其他协程由当前协程来控制。目前的协程框架一般都是设计成 1:N 模式。因为协程不是抢占式的,你的代码中必须标注出什么时候可以安全地暂停执行当前任务,让位给其他任务运行。

抢占调度策略:支持中断正在运行的进程,将主动权掌握在操作系统这里,通常开销会更大。 非抢占调度策略:让进程运行到结束,阻塞或主动让出控制权。

优点

  1. 协程更加轻量,创建成本更小,降低了内存消耗。
  2. 协作式的用户态调度器,减少了 CPU 上下文切换的开销,提高了 CPU 缓存命中率。
  3. 减少同步加锁,整体上提高了性能。
  4. 可以按照同步思维写异步代码,即用同步的逻辑,写由协程调度的回调。

缺点

  1. 在协程执行中不能有阻塞操作,否则整个线程被阻塞(协程是语言级别的,线程,进程属于操作系统级别)。
  2. 需要特别关注全局变量、对象引用的使用。
  3. 协程可以处理 IO 密集型程序的效率问题,但是处理 CPU 密集型不是它的长处。

适用场景

  1. 高性能计算,牺牲公平性换取吞吐。协程最早来自高性能计算领域的成功案例,协作式调度相比抢占式调度而言,可以在牺牲公平性时换取吞吐。
  2. IO Bound 的任务。
  3. Generator 式的流式计算消除 Callback Hell(回调地狱)。

Lua中的协程

// 单任务
function fibonacci()
  local m = 1
  local n = 1

  while true do
    coroutine.yield( m ) // 挂起协程
    m, n = n, m + n
  end
end

local generator = coroutine.create(fibonacci)   // 创建协程
succeeded, value = coroutine.resume(generator)  // 得到结果,重启协程

print(succeeded)  // true
print(value) // 1
// 多任务
// scheduler.lua
local pending = {}

local function sort_by_time(array)
  table.sort(array, function(e1, e2)
      return e1.time < e2.time
    end
  )
end

local function wait(seconds)
  coroutine.yield(seconds)
end

local function remove_first(array)
  local result = array[1]
  array[1] = array[#array]
  array[#array] = nil
  return result
end

local function schedule(time, action)
  pending[#pending + 1] = {
    time = time,
    action = action
  }

  sort_by_time(pending)
end

local function run()
  while #pending > 0 do
    while os.clock() < pending[1].time do end

    local item = remove_first(pending)
    local _, seconds = coroutine.resume(item.action)

    if seconds then
      later = os.clock() + seconds
      schedule(later, item.action)
    end
  end
end

return {
  schedule = schedule,
  run = run,
  wait = wait
}

// punch.lua
local scheduler = require("scheduler")

function punch()
  for i = 1, 5 do
    print('punch' .. i)
    scheduler.wait(1.0)
  end
end

function block()
  for i = 1, 3 do
    print('block' .. i)
    scheduler.wait(2.0)
  end
end

scheduler.schedule(0.0, coroutine.create(punch))
scheduler.schedule(0.0, coroutine.create(block))

scheduler.run()

// punch1
// block1
// punch2
// block2
// punch3
// punch4
// block3
// punch5