Title says it all, I want to convert/clone a SharedTable into a normal table format, for saving as a string using JSONEncode. However it was a surprise to discover that the SharedTable global has no methods for converting between the two, and methods of iteration such as pairs don’t work on them.
For arrays, I can take advantage of the SharedTable.size function to create a table version:
local function copyArray(s: SharedTable): {}
local t = {}
for i = 1, SharedTable.size(s) do
table.insert(t, s[i])
end
return t
end
However I don’t have a solution for dictionaries that doesn’t include a brute force approach. Any help on how to fetch the keys or how to copy the shared table as a table all together is appreciated.
Keep in mind direct indexing of shared tables is supported, however in order for this to be useful the shared table structure needs to be known before hand, and this assumption isn’t true here.
I’ll disclose that prior to seeing your post I had no idea what a shared table was. I’ve done a bit of research and some testing, and figured out that you can still iterate through key val pairs (or index val pairs) by doing something like
for key, val in s do -- where s is a SharedTable
print(key, val)
end
Based on this, I modified your function such that it works for both tables and arrays (and can work recursively if there are shared tables within the initial shared table):
local function copyArray(s: SharedTable): {}
local t = {}
for key, val in s do
if typeof(val) == "SharedTable" then
t[key] = copyArray(val)
else
t[key] = val
end
end
return t
end
Nice catch! My coding habit of using the pairs statement prevented me from finding this solution. I decided to go down a more painful path in the meantime, which I’ll add it here as a hacky solution for anyone interested:
game.LogService.MessageOut:Once(function(t)
print(t)
end)
print(s) --this costs us a message in the output
What the t variable holds is a lua-like string encoded version of the shared table, that doesn’t maintain the type of the values passed in(all of them are shown as words/strings). What I thought of is fetching this string, writing a parser, fetching a tree-like structure of the keys of the shared table, then using direct indexing to get the values in their correct format, and eventually create a table copy.
Obviously your solution is more optimal, I just add it as an extra hacky idea.
I also use pairs / ipairs pretty much constantly. Very rarely do I neglect to use them.
(While on the topic of old habits - for the text with the dark background, you only need to put one `, instead of 3 (`TEXT` instead of ```TEXT```)
Your solution certainly seems … unpleasant, to say the least xD