lua使用记录

记录使用lua过程中遇到的问题

1. 字符串操作

截去字符串首尾空格

1
string.gsub(str, "^%s*(.-)%s*$", "%1")  --截掉前后空格

2. 获取指点年月有多少天

1
2
3
4
5
6
7
8
9
10
11
12
13
function getDayByYearMonth(_year, _month)
local _curYear = tonumber(_year)
local _curMonth = tonumber(_month)
if not _curYear or _curYear <= 0 or not _curMonth or _curMonth <= 0 then
return
end
local _curDate = {}
_curDate.year = _curYear
_curDate.month = _curMonth + 1
_curDate.day = 0
local _maxDay = os.date("%d",os.time(_curDate))
return _maxDay
end

3. 贪心算法(找钱算法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function GetChipsFromNum(num)
if not num then return end
gLog("--- 开始找钱")
local chipType = {1, 2, 5, 10, 50, 100, 500, 1000, 5000}
-- 排序
table.sort(chipType, function(a, b)
return a > b
end)
local changeTbl = {}
for k,value in pairs(chipType) do
local zheng_shu = math.floor(num/value)
local yu_shu = num%value
if zheng_shu ~= 0 then
num = yu_shu
table.insert(changeTbl, {chipsType = value, num = zheng_shu})
gLog("币种:{2}-- 数量:{0} --- 余数:{1}", zheng_shu, yu_shu, value)
end
end
return changeTbl
end

4. cannot use ‘…’

使用可变长参数,遇到如下

1
cannot use '...' outside a vararg function near '...'

出现问题示例:

1
2
3
4
5
6
7
8
9
local testFn = function(cb)
cb()
end

local testFn2 = function(cb, ...)
testFn(function()
cb(...)
end)
end

引发错误原因:不可以在一个可变长参数函数的外部使用…,因为 … 是匿名的,lua5.1以后不再为vararg自动创建一个表,需要我们手动创建表:

1
2
3
4
5
6
7
8
9
10
local testFn = function(cb)
cb()
end

local testFn2 = function(cb, ...)
local args = {...}
testFn(function()
cb(unpack(args))
end)
end