This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
KingofGamesYami's profile picture

[SOLVED]Help with Table to String

Started by KingofGamesYami, 18 April 2014 - 06:02 AM
KingofGamesYami #1
Posted 18 April 2014 - 08:02 AM
table = {"A", "B", "C")
Is there any way I can convert this to
tString = "ABC"
Without knowing how many variables I have stored?

Question was answered here : http://stackoverflow.com/questions/23148716/can-i-connect-the-variables-in-a-table
Edited on 18 April 2014 - 06:08 AM
Wojbie #2
Posted 18 April 2014 - 08:08 AM
You want to use table.concat() for that. for more info about that function see here.
Edited on 18 April 2014 - 06:08 AM
KingofGamesYami #3
Posted 18 April 2014 - 08:09 AM
You want to use table.concat() for that. for more info about that function see here.
I ninja'd you while editing my main post… LOL
Dog #4
Posted 18 April 2014 - 08:09 AM
EDIT: Ninja'd

Yes. You would use #table to find the number of variables stored. For example:

for i = 1,#table do

Then you would use the double dot/period ( .. ) to concatenate each one onto the other like so

newString = newString .. table[i]

If you need a more explicit example let me know. One other thing - it's not a good idea to name your table "table" - especially if you don't localize the variable name 'table'
Edited on 18 April 2014 - 06:09 AM
theoriginalbit #5
Posted 18 April 2014 - 08:11 AM
do note however that table.concat only works on indexed tables, ergo any values stored under a key will not appear in the resultant string.
KingofGamesYami #6
Posted 18 April 2014 - 08:34 AM
EDIT: Ninja'd

Yes. You would use #table to find the number of variables stored. For example:

for i = 1,#table do

Then you would use the double dot/period ( .. ) to concatenate each one onto the other like so

newString = newString .. table[i]

If you need a more explicit example let me know. One other thing - it's not a good idea to name your table "table" - especially if you don't localize the variable name 'table'
Yeah, I know. That was an example. My actual code is long and mostly irrelevant (making a virtual keyboard on screen :P/>)
do note however that table.concat only works on indexed tables, ergo any values stored under a key will not appear in the resultant string.
I assumed it would… How would it know which comes first otherwise? Not a problem in this case.
apemanzilla #7
Posted 18 April 2014 - 01:06 PM
If for some reason you have non-number indices, you'd need to loop through the table with the "pairs" function:

local tbl = {}
tbl[1] = "a"
tbl["a"] = "b"
local str = ""
for _,v in pairs(tbl) do
  str = str..v
end
Please note however the order may not be preserved when this method is used.