【Lua】基础工具封装分享

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)
	-- 缓存table地址,防止递归死循环
	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

	-- 处理直接传入table的情况
	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))
					-- 如果是table模拟的类,忽略。 以下划线开头的字段, 忽略
				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 为小数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值