Lua practices

Table of Contents

1 简介

2 语言

2.1 scope

local a = 10
local a,b = 1,2
print(a,b)

2.2 metatable


-- -*- coding:utf-8 -*-

2.3 Class

-- -*- coding:utf-8 -*-
Person = {name="noname"}

function Person.new(name)
    local p = setmetatable({}, Person)
    p.name = name
    return p
end

function Person:say(str)
    print(self.name .. " say " .. str)
end

local john = Person.new("john")
john:say("hello")

local nobody = Person.new()
nobody:say("hello")

3 os

-- -*- coding:utf-8 -*-

local os = require("os")
os.execute("ls")

4 regex

5 string

5.1 find

5.2 gmatch

local example = "an"
for i in string.gmatch(example, "[^,]+") do
  print(i)
end
local function split(s,p)
    local m = {}
    for i in string.gmatch(s, string.format("[^%s]+",p)) do
        table.insert(m,i)
    end
    return m
end

local m = split("1,2", ',')
for i,v in ipairs(m) do
    print(v)
end

6

6.1 cjson1

6.1.1 encode

6.1.2 decode

需要注意的是所有使用数字作为 key 的 json object 解码之后,数字 key 都会变为 lua 字符串存储。

Footnotes:

Author: lsl

Created: 2016-08-07 Sun 19:36

Validate