Converting string to CFrame

I’m looking for a way to convert a string into a cframe, the string that has to be converted looks like this:

“4.49657869, 3.69892478, -3.5816226, 1, 0, 0, 0, 1, 0, 0, 0, 1”

I tried doing:
CFrame.new(4.49657869, 3.69892478, -3.5816226, 1, 0, 0, 0, 1, 0, 0, 0, 1)
CFrame.new("4.49657869, 3.69892478, -3.5816226, 1, 0, 0, 0, 1, 0, 0, 0, 1")

I want to make it so you can do:
Model:SetPrimaryPartCFrame(ConvertedToCFrame)

Can anyone help?

2 Likes

First, turn the string into a table using HttpService.

local cf_string = '4.49657869, 3.69892478, -3.5816226, 1, 0, 0, 0, 1, 0, 0, 0, 1'

local http = game:GetService('HttpService')
local cf_table = http:JSONDecode('['..cf_string..']') --put brackets around the string to format it into JSON

Then, create the CFrame after unpacking the table:

local cf = CFrame.new(unpack(cf_table)) --unpack() turns the table's indexes into separate parameters

Here’s a function that does it all:

function stringToCFrame(input)
  return CFrame.new(
    unpack(
      game:GetService('HttpService'):JSONDecode(
        '['..input..']'
      )
    )
  )
end

--example
print(stringToCFrame('1, 2, 3, 1, 0, 0, 0, 1, 0, 0, 0, 1')) --prints out the CFrame

(I haven’t tested any of the code, should work)

1 Like
function stringtocf(str)
 return CFrame.new(table.unpack(str:gsub(" ",""):split(",")))
end

First remove the whitespace, then get every number after each comma and put it in the CFrame

10 Likes

JSONDecode is super slow and a hacky approach. Just do string.split with , (a comma followed by a space, in case Discourse’s formatting makes it unclear) as the separator.

2 Likes

I ended up using:

function StringToCFrame(String)
    local Split = string.split(String, ",")
    return CFrame.new(Split[1],Split[2],Split[3],Split[4],Split[5],Split[6],Split[7],Split[8],Split[9],Split[10],Split[11],Split[12])
end

But the original solver deleted hist post, and I had to give someone the solution.

3 Likes

You can just unpack, Luffy’s solution is better.

6 Likes