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

Turn a table into a StringValue?

Asked by 10 years ago

Simple question. With a simple answer i hope...

So how could i do this? I have a table containing the loadout of a class within my game, and i need to send the table to a StringValue inside a Configuration folder for the player.

Any help would be appreciated. :)

Edit: The table doesn't contain any bools or numbers. Just worth noting.

1 answer

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

The problem of turning objects into strings is called serialization.

Serializing a table is difficult for the following reasons:

  • Table keys aren't just numbers
  • Tables can contain more tables
  • Delimiters for entries are allowed in strings
  • Tables can be recursive (tab[1] == tab can happen)

If you use the RbxUtility library, you can use the EncodeJSON function to turn a table into a string, and the DecodeJSON to turn a string into a table.

JSON is a serialization method developed to support JavaScript, but it adapts very well to Lua objects (excepting that it cannot manage recursive entries or non-stringly keys)


If your tables are something simple, e.g., your table is only a list of words that you know never contain some particular character (like the newline "\n") then you can just put them together and then break it apart by those:

function wordListToString(list)
    return table.concat(list, "\n");
end

function stringsplit(self, sep)
    -- From lua users wiki
        local sep, fields = sep or ":", {}
        local pattern = string.format("([^%s]+)", sep)
        self:gsub(pattern, function(c) fields[#fields+1] = c end)
        return fields
end

function stringToWordList(str)
    return stringsplit(str, "\n");
end
Ad

Answer this question