Lua 工具封装
lua 字符串分割
function luaStringSplit(str, split_char)
local sub_str_tab = {};
while (true) do
local pos = string.find(str, split_char);
if (not pos) then
sub_str_tab[#sub_str_tab + 1] = str;
break;
end
local sub_str = string.sub(str, 1, pos - 1);
sub_str_tab[#sub_str_tab + 1] = sub_str;
str = string.sub(str, pos + 1, #str);
end
return sub_str_tab;
end
lua table 转 string 一般输出日志时使用
function TabToStr = function(sign, tab, showAddress)
local tabs = {};
local check = function(cur_tab, key, parentKey, level)
local tempP = tabs[(level-1) .. parentKey]
while tempP do
if tempP.id == tostring(cur_tab) then
return false;
end
tempP = tempP.parent;
end
tabs[level .. key] = {};
tabs[level .. key].id = tostring(cur_tab);
tabs[level .. key].parent = tabs[(level-1) .. parentKey];
return true;
end
if tab == nil then
tab = sign;
sign = "table:";
end
local targetType = type(tab);
if targetType == "table" then
local isHead = false;
local function dump(t, tKey, space, level)
local temp = {};
if not isHead then
temp = {sign or "table:"};
isHead = true;
end
if tKey ~= "_fields" then
table.insert(temp, string.format("%s{", string.rep(" ", level)));
end
for k, v in pairs(t) do
local key = tostring(k);
if key == "_fields" then
local fields = {};
for fk, fv in pairs(v) do
fields[fk.name] = fv;
end
table.insert(temp, dump(fields, key, space, level))
elseif key == "class" or string.sub(key, 1, string.len("_")) == "_" then
elseif type(v) == "table" then
if check(v, key, tKey, level) then
if showAddress then
table.insert(temp, string.format("%s%s: %s\n%s", string.rep(" ", level+1), key, tostring(v), dump(v, key, space, level + 1)));
else
table.insert(temp, string.format("%s%s: \n%s", string.rep(" ", level+1), key, dump(v, key, space, level + 1)));
end
else
table.insert(temp, string.format("%s%s: %s (loop)", string.rep(" ", level+1), key, tostring(v)));
end
else
table.insert(temp, string.format("%s%s: %s", string.rep(" ", level+1), key, tostring(v)));
end
end
if tKey ~= "_fields" then
table.insert(temp, string.format("%s}", string.rep(" ", level)));
end
return table.concat(temp, string.format("%s\n", space));
end
return dump(tab, "", "", 0);
else
return tostring(tab);
end
end
lua 把float 转整数 和小数
local n1,n2 = math.modf(SumPayGold)
n1 为整数
n2 为小数