Serialization 将序列化数据加载到表中
作为回答,我想将一些序列化的lua代码加载到一个表中。要加载的字符串的格式如下:Serialization 将序列化数据加载到表中,serialization,lua,deserialization,Serialization,Lua,Deserialization,作为回答,我想将一些序列化的lua代码加载到一个表中。要加载的字符串的格式如下: SavedVars = { } SavedStats = { } { ["SavedVar"] = { }, ["SavedStats"] = { } } (其中,{…}中的每一个都可能是任何Lua表达式,包括带有嵌套数据的表构造函数。我假设它没有调用任何(全局)函数或使用全局变量 我最后想要的是这样一张表格: SavedVars = { } SavedStats = { } { ["SavedVar
SavedVars = { }
SavedStats = { }
{ ["SavedVar"] = { }, ["SavedStats"] = { } }
(其中,{…}
中的每一个都可能是任何Lua表达式,包括带有嵌套数据的表构造函数。我假设它没有调用任何(全局)函数或使用全局变量
我最后想要的是这样一张表格:
SavedVars = { }
SavedStats = { }
{ ["SavedVar"] = { }, ["SavedStats"] = { } }
我不希望在以后使用全局变量savedvar
。
如何做到最优雅
(我已经找到了解决方案,但可能有人有更好的。)以下是我的解决方案:
-- loads a string to a table.
-- this executes the string with the environment of a new table, and then
-- returns the table.
--
-- The code in the string should not need any variables it does not declare itself,
-- as these are not available on runtime. It runs in a really empty environment.
function loadTable(data)
local table = {}
local f = assert(loadstring(data))
setfenv(f, table)
f()
return table
end
它使用loadstring
加载数据字符串,然后使用将函数的全局环境修改为一个新表。然后调用加载的函数填充该表(而不是全局环境),然后我们可以返回该表
将环境设置为新表会导致代码根本无法使用任何全局数据。我认为这是对代码进行沙箱处理的一种好方法,但如果不需要,可以在返回表之前填充表或为其提供一些元表(但在返回表之前取消设置)
此加载函数还可以处理中生成的序列化数据。以下是我的解决方案:
-- loads a string to a table.
-- this executes the string with the environment of a new table, and then
-- returns the table.
--
-- The code in the string should not need any variables it does not declare itself,
-- as these are not available on runtime. It runs in a really empty environment.
function loadTable(data)
local table = {}
local f = assert(loadstring(data))
setfenv(f, table)
f()
return table
end
它使用loadstring
加载数据字符串,然后使用将函数的全局环境修改为一个新表。然后调用加载的函数填充该表(而不是全局环境),然后我们可以返回该表
将环境设置为新表会导致代码根本无法使用任何全局数据。我认为这是对代码进行沙箱处理的一种好方法,但如果不需要,可以在返回表之前填充表或为其提供一些元表(但在返回表之前取消设置)
这个加载函数也可以使用中生成的序列化数据。您知道吗,
{[“SavedVar”]={},[“SavedStats”]={}}
也可以写成{SavedVar={},SavedStats={}}
?@lhf:是的,但这并不重要-我只是想要Lua中的表,而不是字符串输出。您知道吗{[“SavedVar”]={},[“SavedStats”]={}}
也可以写成{SavedVar={},SavedStats={}
?@lhf:是的,但这在这里并不重要-我只是想要Lua中的表,而不是字符串输出。