是一个字符串必须小于存储中的Vector3吗?



我正在Core中制作一个系统来保存家具的变换,特别是位置和旋转,这两个都是Vector3的。我把这些放在播放器存储中,所以在某个时刻,为了保存所有播放器的家具,我想我最终会耗尽播放器存储空间。所以我将所有的Vector3转换为字符串,使用我发现的Roblox脚本的修改版本:

local API = {}
API.VectorToString = function(vec)
return math.floor(vec.x*100)/100 ..' '.. math.floor(vec.y*100)/100 ..' '.. math.floor(vec.z*100)/100
end
API.StringToVector = function(str)
local tab = {}
for a in string.gmatch(str,"(%-?%d*%.?%d+)") do
table.insert(tab,a)
end
return Vector3.New(tab[1],tab[2],tab[3])
end
return API

所以问题是,转换所有这些向量到字符串实际上节省空间在我的播放器数据存储?

在存储方面,Vector3格式很可能比字符串转换更有效。Vector3中的每个数字需要存储4个字节,因为每个数字都是16位浮点数。通过将Vector3值转换为字符串,需要额外的字节(您添加的每个数字需要一个字节,因为一个字符需要一个字节)。如果你需要将Vector3存储为字符串,我建议使用下面的方法。

对于任何想了解计算机如何在四个字节内存储如此广泛的数字的人,我强烈建议研究IEEE 754格式。

说明IEEE754格式的视频

可以使用字符串。和string.unpack将浮点数转换为可以作为字符串发送的字节数组的函数。这种方法在发送数据时总共只需要12个字节(12个字符),并且具有大约5到6个小数点的精度。虽然这种方法可能只节省几个字节,但它将允许您发送/保存更精确的数字/位置。

local API = {}
API.VectorToString = function(vec) 
--Convert the x,y,z positions to bytes 
local byteXValue = string.pack('f', vec.x, 0) 
local byteYValue = string.pack('f', vec.y, 0) 
local byteZValue = string.pack('f', vec.z, 0) 
--Combine the floats bytes into one string
local combinedBytes = byteXValue + byteYValue + byteZValue
return combinedBytes 
end
API.StringToVector = function(str) 
--Convert the x,y,z positions from bytes to float values
--Every 4th byte represents a new float value
local byteXValue = string.unpack('f', string.sub(1, 4)) 
local byteYValue = string.unpack('f', string.sub(5, 8)) 
local byteZValue = string.unpack('f', string.sub(9, 12)) 
--Combine the x,y,z values into one Vector3 object
return Vector3.New(byteXValue, byteYValue, byteZValue) 
end
return API

字符串包功能文档

可以写得更短一些,占用更少的内存

local v3 = Vector3.New(111, 222, 333)
local v3str = string.pack("fff", v3.x, v3.y, v3.z)
local x, y, z = string.unpack("fff", v3str)
local v31 = Vector3.New(x, y, z)
assert(v3 == v31)

但是你需要记住,大多数核心API函数不允许字符串中的零字节,如果你想将这些字符串存储在Storage中或将它们用作事件参数-你应该对它们进行文本编码(Base64是一个常见的选项)。

最新更新