Lua 编程入门

1.24

介绍

Lua 是一门轻量级、可嵌入的动态脚本语言。

安装 / 编译

  • 可以直接下载可执行二进制文件

  • 或者下载源码编译

    curl -R -O http://www.lua.org/ftp/lua-5.3.5.tar.gz
    tar zxf lua-5.3.5.tar.gz
    cd lua-5.3.5
    
    # For Linux
    make linux test
    
    # For MacOS
    make macosx test
    

运行

test.lua

print('Hello World!')

In terminal, run

lua test.lua

语法

快速入门: Learn Lua in 15 Minutes

完整介绍: Programming in Lua

Comment

-- Comment

--[[
    Multi-line comment
--]]

Print messages

print('Hello World!')

Variables and flow control

num = 42
s1 = 'water'
s2 = "double quotes are also fine"
s3 = [[ Double brackets start and end
  multi-line strings.]]
nothing = nil

boolValue = false

answer = boolValue and 'yes' or 'no'

while num < 50 do
  num = num + 1
end

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

repeat
  print('running')
  num = num - 1
until num == 0

if num > 40 then
  print
elseif s ~= 'water' then
  io.write('not equal water')
else
  globalVar = 5

  local line = io.read()
  print('input' .. line)
end

Functions

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

-- Closures and anonymous functions
function adder(x)
  return function (y) return x + y end
end

a1 = adder(9)
print(a1(16)) --> 25

-- Calls with one literal param don't need parens
print 'hello'

Tables

Table 是唯一的复合数据结构,用作 dictionaries / maps。类似于 PHP arrays 或 JavaScript objects。

t = { key1 = 'value1', key2 = false }
t.key3 = {}
t.ke12 = nil -- Removes key2 from the table

-- Use paris() for key-value table
for key, value in paris(t) do
  print(key, value)
end

-- Table with int keys, starts at 1 !!
listTable = { 'value1', 'value2', 1.21 }
for i = 1, #listTable do
  print(listTable[i])
end

-- Use ipairs() for index-value table, which is like array/list
for i, item in ipairs(listTable) do
  print(item)
end

对 table 可以设置 metatable。类似于 JavaScript 的 prototype。

f1 = { a = 1, b = 2 }
f2 = { a = 2, b = 3 }

metafraction = {}
function metafraction.__add(f1, f2)
    sum = {}
    sum.b = f1.b*f2.b
    sum.a = f1.a*f2.b + f2.a*f1.b
    return sum
end

setmetatable(f1, metafraction) -- Use getmetatable(f1) to retrieve it.
setmetatable(f2, metafraction)
s = f1 + f2 -- Call __add(f1, f2) on f1's metatable

__index 用于递归的属性查找

defaultFavs = { animal = 'gru', foold = 'donuts' }
myFavs = { foold = 'pizza' }
setmetatable(myFavs, { __index = defaultFavs })
eatenBy = myFavs.animal

Classes

Classes 不是内置的类型。需要使用 table 和 metatable 实现。

Dog = {}

-- function tablename:fn(...) is the same as 
-- function tablename.fn(self, ...)
function Dog:new()
  newObj = { sound = 'woof' }
  self.__index = self
  return setmetatable(newObj, self)
end

function Dog:makeSound()
  print('I say ' .. self.sound)
end

mrDog = Dog:new()
mrDog:makeSound() -- I say woof

Modules

以文件为单位定义模块,可以看成独立的函数。

mod.lua

local M = {}

local function sayMyName()
  print('Hrunkner')
end

function M.sayHello()
  print('Why hello there')
  sayMyName()
end

return M

main.lua

-- require runs the module file once with caching
local mod = require('mod')
mod.sayHello()

-- just require and run
require 'mod'

-- require acts like
local mod = (function ()
  -- <contents of mod.lua>  
end)()


-- dofile is like requrie without caching
dofile('mod.lua')
dofile('mod.lua')

-- loadfile loads a lua file but doesn't run it yet
f = loadfile('mod.lua') -- call f() to run it.

-- load is loadfile for strings
g = load('print(123)') -- call g() to run it.
📖