[游戏开发] LuaTable转string存读二进制文件

UE5和Unity通用此方案,只不过读写文件的接口略有不同,lua代码的处理是相同的。

下面两个方法是 LuaTable和字符串互相转换的代码

Lua 复制代码
function XUtils.luaTableToString(tab, sp)
	sp = sp or ""
	local s = ""
	for k,v in pairs(tab) do
		if type(k) == "number" then
			k = _strFormat("[%s]", k)
		end
		if type(v) == "table" then
			s = _strFormat("%s %s=%s,",s, k, XUtils.luaTableToString(v))
		elseif type(v) == "string" then
			s = _strFormat("%s %s='%s',",s, k, v)
		else
			s = _strFormat("%s %s=%s,",s, k, v)
		end
		s = _strFormat("%s%s",s,sp)
	end
	return _strFormat("{%s%s}",sp,s)
end

function XUtils.stringToLuaTable(str)
	if string.isEmpty(str) then
		return {}
	end
	local tab
	local bSucc, _ = xpcall(function()
		tab = load( "return "..str )()
	end, __G__TRACKWARN__)
	if not bSucc then
		return {}, false
	end
	return tab
end

获取UE5本地存储地址:

Lua 复制代码
local function GetPath()
	local userId = GetLocalDataAvatarDID(BP_GameInstance_Inst)
	local filePath = UE.FPaths.ProjectSavedDir() .. string.format( "localdata_%s.bin", v~=0 and v or "def")
	return filePath 
end

存储代码:_defData 是我想存的LuaTable对象,SaveStringToFile方法把字符串转二进制并存到目标路径文件里

Lua 复制代码
local function SaveDef_()
	local filePath = GetPath()
	local str = XUtils.luaTableToString(_defData or {}, "\n")
	local ret = UE.FFileHelper.SaveStringToFile(str, filePath)
end

存储后的文件长这样子

读取二进制存档,把二进制文件读成string,再把string解析成luaTable

Lua 复制代码
local function Init_()
	local filePath = GetPath()
	if UE.FPaths.FileExists(filePath) then
		local fileString = UE.FFileHelper.LoadFileToString(filePath)
		local luaTable = XUtils.stringToLuaTable(fileString)

		--拿到luaTable数据
	end
end

到此成功完成了

相关推荐
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1236 天前
matlab画图工具
开发语言·matlab
dustcell.6 天前
haproxy七层代理
java·开发语言·前端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone6 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054966 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月6 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237176 天前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian6 天前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript
雪人不是菜鸡6 天前
简单工厂模式
开发语言·算法·c#