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

Is there an easier way to dump a table?

Asked by 6 years ago

I have a table in a data store which has a table inside of it. When I tried accessing that table or printing it, it just gave a hexadecimal output. Looping through the table did not work for me either. So after some research and questioning I implemented these two functions to get the data:

    local function dumpTable(tableToDump)

        local tbl = {}

        if type(tableToDump) == "table" then

            for i,v in pairs(tableToDump) do

                wait()

                table.insert(tbl, tostring(v))

            end

            return "{" .. table.concat(tbl, ", ") .. "}"

        else

            return nil

        end
    end

    local function changeStringToTable(tbl)

        local finishedTable = {}    

        for int in string.gmatch(tbl, "%d+") do

            table.insert(finishedTable, tonumber(int))

        end

        return finishedTable    

    end

Is there an easier/more effective way of going about this? Thanks!

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

Roblox has in-built functions to convert tables to string values and vice versa.

JSONEncode and JSONDecode in HttpService

Here's some code from the wiki on how to encode a json string. It's very simple:

local HttpService = game:GetService("HttpService")

local tab = {
    -- Remember: these lines are equivalent
    ["message"] = "succes";
    message = "success";

    info = {
        points = 120,
        isLeader = true,
        user = {
            id = 12345,
            name = "JohnDoe"
        },
        past_scores = {50, 42, 95},
        best_friend = nil
    }
}

-- A cyclic relationship like this...
tab.tab = tab
-- ...will be replaced with the string:
-- '* certain entries belong to the same table '*

local json = HttpService:JSONEncode(tab)
print(json)

0
Roblox already JSONEncodes the datastore requests. User#21908 42 — 6y
Ad

Answer this question