How would I go about converting tables, no matter what their dimensions are, into strings? I really don’t know where to start.
What’s your use case? And how would you want the string formatted?
If you literally want the entire table as a string: you can always convert a lua table to JSON (a string) by using HttpService:JSONEncode.
I’ve tried that but sometimes there’s player instances at random places in the arrays.
okay this seems to work
function GetTableAsString(Table)
local String = ""
local function GetAsString(Tab)
local _String = ""
for i, v in pairs(Tab) do
if (typeof(v) == "string") then
_String = _String .. (i>1 and " " or "") .. v
elseif (typeof(v) == "table") then
local asString = GetAsString(v)
_String = _String .. (i>1 and " " or "") .. asString
end
end
return _String
end
for i, v in pairs(Table) do
local _String
if (typeof(v) == "string") then
_String = v
elseif (typeof(v) == "table") then
_String = GetAsString(v)
end
String = String .. (i>1 and " " or "") .. _String
end
return String
end
If it’s just an array, you can do
local array = {2, plr, "there"}
for i, v in ipairs(array) do
local convertedString = tostring(array[i])
print(convertedString)
end
Output
- 2
- AbiZinho
- there
What are your motives for this code?
If it’s just an array, you can use JSONEncode
like @Fm_Trick mentioned. Your code also doesn’t convert it to a string, it just prints all the values in the table.
You aren’t converting the table to a string, you are just printing the values in the table. There’s also no difference between print(x)
and print(tostring(x))
as print
does this automatically (you can test this with print(Vector3.new(1,2,3))
or print(workspace)
or really printing any userdata object)
Converting the values in a table to be strings is not the same as converting a table to a string.
I stated print()
out of the blue as filler code. The main focus here is that the value is converted into a string, and can be used in a context where a string is generally needed.
I’m not sure you understand, the original post was asking to be able to convert a table to a string, not to make the values of a table be strings.
I could be misunderstanding the original post, but the code he posted and the mention of JSONEncode
by the other person makes it seem like that’s what he wants.
I can fork the code accordingly then:
local str = ''
local array = {2, plr, "there"}
for i, v in ipairs(array) do
str = str, tostring(v)
end
print(str)
Output
- 2 AbiZinho there
Yeah you’re correct. I wanted to be able to convert something like
local tab = {‘a’, {‘b’, {‘c’}}, {‘d’}}
into just “a b c d” — and the function I made does that (or at least I’m 99% sure it does)
Then JSONEncode
would be sufficient for this. I thought you had a simple array, my bad.
No because some of my arrays had Player instances so it wouldn’t have worked correctly
I just found a resource that does exactly this, with little to no limitations!