游戏脚本制作过程中需要持久化部分数据,经过技术可用性分析,字符串与表互转不可以再游戏中持久化。存储到本地IO 成本也比较高,可以尝试一下。

需要准备三个方法

function ToStringEx(value)
    if type(value)=='table' then
       return TableToStr(value)
    elseif type(value)=='string' then
        return "\'"..value.."\'"
    else
       return tostring(value)
    end
end

function StrToTable(str)
    if str == nil or type(str) ~= "string" then
        return
    end
    
    return loadstring("return " .. str)()
end

function TableToStr(t)
    if t == nil then return "" end
    local retstr= "{"

    local i = 1
    for key,value in pairs(t) do
        local signal = ","
        if i==1 then
          signal = ""
        end

        if key == i then
            retstr = retstr..signal..ToStringEx(value)
        else
            if type(key)=='number' or type(key) == 'string' then
                retstr = retstr..signal..'['..ToStringEx(key).."]="..ToStringEx(value)
            else
                if type(key)=='userdata' then
                    retstr = retstr..signal.."*s"..TableToStr(getmetatable(key)).."*e".."="..ToStringEx(value)
                else
                    retstr = retstr..signal..key.."="..ToStringEx(value)
                end
            end
        end

        i = i+1
    end

     retstr = retstr.."}"
     return retstr
end

具体使用

	local tb = {
		[1] = "A";
		[2] = "B";
		[3] = "C";
		[4] = "D";
	}

	-- 表转字符串
	local strtb = TableToStr(tb)
	print(strtb)

	-- 字符串转表
	local newtb = StrToTable(strtb)
	for k,v in ipairs(newtb) do
        	print(k,v)
	end