Setting HumanoidDescription using table values

-- Setting the players hats
print('Loading:', #hats, unpack(hats)) -- Loading: 3 15967743 16101707 162066057
User.Character.HatAccessories = hats

However, when I try this

print(tostring(unpack(User.Character.HatAccessories))) -- 15967743
HumanoidDescription.HatAccessory = tostring(unpack(User.Character.HatAccessories))

It only prints 1 of their accessories, even tho there’s 3, and thus it only gives them the one hat, not all 3

unpack returns a tuple. tostring does not take varargs, thus forcing the tuple’s size to 1 which is why only 1 of the items is being returned. What you should do instead is parse the tuple returned from unpack into a string and set it as HatAccessory accordingly.

And how exactly do I do that? :sweat_smile:

Simple iteration with a string to concatenate to. You can do it directly from its array state and completely skip unpacking the table.

local function arrayToString(array)
    local retString = ""

    for i, element in ipairs(array) do
        retString = retString..tostring(element)
        if not (i == #array) then
            retString = retString..", "
        end
    end

    return retString
end

local TestArray = {"A", "B", "C"}
print(arrayToString(TestArray)) -- A, B, C

This function also adds in the commas needed to separate the assetIds which is a necessity for the string assigned to a HumanoidDescription. Every element that isn’t the last one gets a comma and a space.

In terms of using unpack, you’d just need to accommodate for varargs. You’d most likely have to end up going right back to a table format for it.

1 Like

table.concat would work fine in this case.

local TestArray = {"A","B","C"}
print(table.concat(TestArray,", "))
--> A, B, C
2 Likes

:man_facepalming:

i literally wrote all that code and forgot about the built-in concatenator for tables LOL

No, it wouldn’t just work fine, it’d work better than what I posted.