Datastores with OOP

If a module script was used to create an object using OOP, is it possible to store that object in a datastore since it is technically a table?
If yes, does that mean functions can also be stored in data stores?

1 Like

No, it is not possible. Remember that when using OOP you use metatables which are not stored in a DataStore (it does not have that support).
On the other hand, in OOP it is typical to handle cross-references or self-references which cannot be stored either.
An object is unique only in the current instance of a Place and there is no guarantee that it will be unique in other instances, so it is not possible to save the object as such.
Although a method or function are also data, a DataStore does not support them, at least not for now.

1 Like

Datastores cannot save the object itself. They can, however, save the properties of a certain object so that you can create an exact clone using the properties you did save. These properties would have to be values that can be saved using the data store.

You could use “LSON” objects (like JSON but Lua :P) where the objects are stored as strings which are also valid Lua syntax. That way you can reconstruct an object from it’s storage format just by using loadstring. For example:

function toLson(t)
    local lson = ""
    if type(t) == "table" then
        lson = lson .. "{\n"
        for k, v in pairs(t) do
            if type(k) == "string" then
                k = '"' .. k .. '"'
            if type(v) == "string" then
                v = '"' .. v .. '"'
            elseif type(v) == "table" then
                v = toLson(v)
            lson = lson .. ("[%s] = %s"):format(k, v) .. ",\n"
        lson = lson .. "}"
    return lson

function fromLson(lson)
    local f, r = loadstring("return " .. lson)
    r = f()
    return r

function printTable(t, tabs)
    local tabs = tabs or 0
    local tabss = ""
    for i = 1, tabs do tabss = tabss .. "\t" end
    print(tabss .. "{")
    for k, v in pairs(t) do
        if type(v) == "table" then
            print(tabss .. ("[%s] = "):format(k))
            printTable(v, tabs + 1)
            print(tabss .. ("[%s] = [%s]"):format(k, v))
    print(tabss .. "}")

local t = {
    [1] = 1,
    [2] = 2,
    [3] = {
        [1] = 4,
        [2] = 5,
    ["hello"] = 99,
local lson = toLson(t)
local q = fromLson(lson)

Not sure if that’s how loadstring works in Roblox :stuck_out_tongue: Anyway you get the idea. Of course only values that can be encoded as literals are valid keys and values.

1 Like

Loadstring will need to be enabled in the game settings for it to work, and can only run on the server’s end (which is fine in this case). But really, you only need to encode to JSON and convert a few potentially non-compatible data-types, but that works too.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.