lua string扩展
lua string常用附加函数
string.split = function(s, delim) local split = {} local pattern = "[^" .. delim .. "]+" string.gsub(s, pattern, function(v) table.insert(split, v) end) return split end string.ltrim = function(s, c) local pattern = "^" .. (c or "%s") .. "+" return (string.gsub(s, pattern, "")) end string.rtrim = function(s, c) local pattern = (c or "%s") .. "+" .. "$" return (string.gsub(s, pattern, "")) end string.trim = function(s, c) return string.rtrim(string.ltrim(s, c), c) end string.split_to_number = function(s, delim) local split = {} local pattern = "[^" .. delim .. "]+" string.gsub(s, pattern, function(v) table.insert(split, tonumber(v)) end) return split end
string格式化一例:
local idStr = string.format("%08x", 15) --把数字15用16进制输出, 占8位, 不足前面补0 print(idStr) -- 输出 0000000f