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

How to convert table to string?

Asked by
Miniller 562 Moderation Voter
5 years ago
Edited 5 years ago

Hello, I have a little code which is for my game. Take a look at the script:

players = game.Players:GetPlayers()

if table.getn(players) >= 4 then
    crim = players[math.random(1, #game.Players:GetPlayers())]
    table.remove(players, players[crim.Name])
    plrs = tostring(players)
    print(plrs)
    print(players)

...

This is in a while true do loop. So I am selecting one player as a criminal, and then removing it from the 'players' table, to make everyone else a police. But when I try to convert the table to a string (to test if it worked), it gives me 'table:' and random characters, such as 13E2F21, both times: print(plrs) and print(players).

My question is, how to convert a table to a string? Sorry for my bad English EDIT: I have tried to comment table.remove(......) with --, but it still not converted the table to string

0
Don't forget to accept my answer if it works. User#24403 69 — 5y

1 answer

Log in to vote
2
Answered by 5 years ago
Edited 5 years ago

It's not random; it's the memory address of the table! If you want to print all the elements of the array, use unpack() since it returns all the elements of a array.

Additionally, you should use the length operator # to get the table length.

players = game.Players:GetPlayers()

if #players >= 4 then
    local num = math.random(1, #players)
    local crim = players[num]
    table.remove(players, num) -- # remove takes the index to remove not value
    print(unpack(players)) -- # print all the elements
    print(players)
end

It would also be prudent to mention table.concat but this only works for string and number elements, and instances are not strings or numbers, so this will fail.

local arr = {"one", "two", "three"}
print(table.concat(arr, ", ")) --> one, two, three

However this is out of the scope of this answer so I will not explain any further.

0
Thank you so much! I am new here, so please, can you tell me how to accept someone's answer? Miniller 562 — 5y
0
I'll do it. ScriptGuider 5640 — 5y
1
Thanks Miniller 562 — 5y
1
Congrats on 2k DinozCreates 1070 — 5y
0
thanks User#24403 69 — 5y
Ad

Answer this question