AboutLUAProgram DesignObject serializationLearning notes are the content to be introduced in this article.LUAMediumObjectOfSerializationFor details, refer to this article.
We usually need to serialize some data, that is, to convert the data into a byte stream or a bytes stream, and then we can easily persist it. There are many formats available for text serialization: SOAP, Json, and even custom xml. However, lua script is also a good choice.
For more information, see 《LuaProgramming version 2nd) "Simplified Chinese version detailed LUA script language data files and persistence based on the Implementation below. Note that this implementation can only target non-circular tables and Cannot serialize or deserialize functions, threads, and userdata. In order to prevent the serialized data from being too large, there is no detailed typographical control.
- function serialize(obj)
- local lua = ""
- local t = type(obj)
- if t == "number" then
- lualua = lua .. obj
- elseif t == "boolean" then
- lualua = lua .. tostring(obj)
- elseif t == "string" then
- lualua = lua .. string.format("%q", obj)
- elseif t == "table" then
- lualua = lua .. "{\n"
- for k, v in pairs(obj) do
- lualua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ",\n"
- end
- local metatable = getmetatable(obj)
- if metatable ~= nil and type(metatable.__index) == "table" then
- for k, v in pairs(metatable.__index) do
- lualua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ",\n"
- end
- end
- lualua = lua .. "}"
- elseif t == "nil" then
- return nil
- else
- error("can not serialize a " .. t .. " type.")
- end
- return lua
- end
-
- function unserialize(lua)
- local t = type(lua)
- if t == "nil" or lua == "" then
- return nil
- elseif t == "number" or t == "string" or t == "boolean" then
- lua = tostring(lua)
- else
- error("can not unserialize a " .. t .. " type.")
- end
- lua = "return " .. lua
- local func = loadstring(lua)
- if func == nil then return nil end
- return func()
- end
-
- data = {["a"] = "a", ["b"] = "b", [1] = 1, [2] = 2, ["t"] = {1, 2, 3}}
- print(serialize(unserialize(1)))
- print(serialize(unserialize(serialize(data))))
Summary: AboutLUAProgram DesignObject serializationThe content of the study notes has been introduced. I hope this article will help you!