Saving restrictions

Why is it that we can only save strings or numbers and not tables or vectors?

Saving tables is not trivial, since they can be nested or have cycles or contain data that’s hard to save and restore such as functions or closures with their associated upvalues. Most of the time it’s better to write your own code, although if you really need something generic then there’s also a lot of existing serialization code, e.g. here: (Not all of this can handle all the special cases you might need, e.g. some can only store tables that contain other tables and strings and numbers but nothing else.)

local str = ""
                for k,v in pairs(Splines) do
                    str = str.."*"
                    for i,j in pairs(v.v) do
                        if i > 1 then
                            str = str.."^"..j.x..","..j.y
                            str = str..j.x..","..j.y
                savedpress = true
                Splines = {}
                local strg = nil
                local strg2 = nil
                local strg3 = nil
                if readLocalData("Splines") ~= nil then
                    strg = readLocalData("Splines")
                    strg = split(strg,"*")
                    for k,v in pairs(strg) do
                    local tbl = {}    
                        strg2 = split(v,"^")
                        for i,j in pairs(strg2) do
                            strg3 = split(j,",")
                            tbl[i] = vec2(strg3[1],strg3[2])

The above two functions save and load a table of vec2, using string seperators “,” “^” and “*”, its just an example i pulled from an old game i was working on, I haven’t come across any bugs with them yet. The key to saving a table is to flatten it in to a string, like above.

You can make loading much simpler and often faster, at the cost of slightly increased size, if you save your data in lua format. E.g. if you want to save a table that only contains numbers:

    tbl = {1,2,3}
    str = table.concat(tbl, ",")
    -- write str to file etc.

Or for a table that only contains vec2’s:

    tbl = {vec2(1,2), vec2(3,4), vec2(5,6)}
    str = ""
    for i,v in ipairs(tbl) do
        str = str.."vec2"..tostring(v)..","

Now, your “load” code is simply this:

    tbl = loadstring("return {"..str.."}")()

Certainly simpler than my way…

Thanks. Is there a way to save a table containing objects for a class. Like if I have a class Block, and I have all Block in a table can i save that? Or will I have to use some other way?

@Sairabh - no, you need to turn your objects into strings