lua
2019-10-26 本文已影响0人
善_8a2f
- 注释
单行
-- this is a comment
多行
--[[
this is a comment
]]
注释内有 "[[ ]]"
--[==[
[[ this is a comment ]]
]==]
- 数据类型
使用type查看
type(nil)
- 字符串
使用 [[ .. ]] 表示 `raw string` , 括号内的字符不会转义
print([[this is raw string \r\n]])
>> this is raw string \r\n
print("this is raw string")
>> this is raw string
print([["",'',""]])
>> "",'',""
---------------
多行字符串
local s = [==[
string
]==]
print(s)
- 比较
比较前需要转为同类型
print(1 > tonumber (" 0 "))
print("13" > "12")
- 逻辑运算
nil 和 false 为 假, 其他都是 真, 包括数字 0;
0 and 'abc' -> 'abc'
nil or 100 -> 100
not nil -> true
利用逻辑运算实现赋值
local y = a and b or c --相当于a?b:c,
- 字符串运算
连接使用 `..`, 不能与nil连接
pirnt("room number is " .. 313)
print("msg is " .. (nil or "-"))
计算长度使用 `#`
print(#"openresty")
>> 9
- 赋值语句
删除变量
foo = nil
- 参数/返回值
local function f1(a,b)
return a+b, a*b
end
local x, y = f1(10, 20)
print(x, ' ', y)
>> 30 200
加括号调用,只返回第一个结果
print((f1(1,2)))
>> 3
- 模块
-- abc.lua
local abc_ = {
version = '1.0',
data = 456
}
function abc_.add(a,b)
return a+b
end
return abc_
-- fff.lua
local abc = require "abc"
local result = abc.add(1,2)
print(result)
- 原型模式
local proto = {}
function proto.go()
print("go pikachu")
end
local obj = setmetatable({}, {__index=proto})
obj.go()
- 代码热加载
-- lua代码热加载
package.loaded.num = loadstring("return 42")
local num = require "num"
print("hot load: ", num())
package.loaded.num = loadstring("return 3.14")
local num = require "num"
print("hot load: ", num())
- 在整个进程共享数据
package.loaded.shared = { ... } -- 存储一段共享数据
- 表
-- 插入元素
a[#a + 1] = 'nginx'
-- 删除指定位置元素, 不能使用arr[n] = nil
local a = {1,2,3}
table.remove(a,2) -> a={1,3}
-- 连接字符串
local a = {'openresty', 'lua}
print(table.concat(a, "+") -> 'openresty+lua'
- math
math.floor(x) , math.ceil(x) -- 向下向上取整
math.min(x,..,), math.max(x,..,) -- 取参数里的最小最大值
math.
- 随机数
math.randomseed(os.time())
for i=1,5 do
print(math.random())
end
- 获取时间
print(os.date("%Y-%m-%d %H:%M:%S"))
- 保护调用
local ok, v = pcall(math.sqrt, 2)
print(ok and v)
local ok, err= pcall(require,"xxx")
if not ok then
print("errinfo is", err)
end