Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to Save Hierarchy into a DataStore and Load It Later?

Asked by
Benbebop 1049 Moderation Voter
4 years ago

In my game players can create their own Guis. I want them to be able to save them between sessions but I'm not sure how to load it back in the next session.

Right now I'm getting the decedents of a folder that contains all the custom Gui then JSON encoding it. When the player rejoins I decode it. How can I take the data I get then recreate the hierarchy from that?

1 answer

Log in to vote
0
Answered by 4 years ago

well you can represent each GUI as an object, let's say you had a hierarchy like the following:

1) screen gui

2) a frame inside the screen GUI

3) a text button inside the frame;

you can represent this like this with lua objects;(a hierarchy like object is called a List, not to be confused with arrays/tables)

local hierarchy = {
    class_name = "ScreenGUI",
    children = {
        frame = {
            class_name = "Frame",
            children = {
                text_button ={}
            }
        }
    }
}

Now this is difficult to look at, but it can be simplified with the concept of classes; here is an example:

function create_instance(class, parent) return { class_name = class, children = {}; parent = parent; } end

the above function "instantiates", i put the quotes around instantiates b/c Lua doesn't have any real concept of classes, you have to be creative about how to make them.

now lets say you want a Roblox hierarchy to be represented as a List, the following should do it

function create_hierarchy(roblox_instance)
    local list = create_instance(roblox_instance.ClassName); --creates the start of the hierachy

    function helper(rbx_item, list_object)
        for _, child_rbx_object in pairs(rbx_item:GetChildren()) do
            local instance = create_instance(child_rbx_object .ClassName, list_object);
            helper(child_rbx_object, instance.Parent)
        end
    end

    helper(roblox_instance, list)
    return list
end

local hierarchy = create_hierarchy(player.PlayerGUI.ScreenGUI);

once that is done, you can turn the hierarchy into a into a string; The HTTP service has functions that turn Lua Objects and Arrays into JSON like string.. i won't go into details, but you can do the following to turn the hierarchy into a string;

local HTTP = game:GetService("HTTPService");

local stringified_object = HTTP:JSONEncode(hierarchy);
print(stringified_object ) --should print a string in output

--you can save `stringified_object ` to datastore b/c it's a string

local back_to_lua_object = HTTP:JSONDecode(stringified_object );

the above should work, if it doesn't then debug it to see the errors in it, as of right now i don't have time to test it.

Ad

Answer this question