String To Vector

How do you convert a string to a vector?

For example “50.5493, 75.3234, 71.8478” to Vector3.new(50.5493, 75.3234, 71.8478)

1 Like

I’d assume you have to use a string pattern to separate this into three parts (three individual strings, not including the spaces and commas in between), then you can straight write a vector statement that uses the results as input.

As for which one you have to use… I don’t know.

Vector3.new(text:match("(.+), (.+), (.+)"))

This could easily be made more specific and strict, but this will work for what you need. (.+) means “all characters” in string formatting, and :match returns a tuple of the groups matched.

5 Likes
local text ="50.5493, 75.3234, 71.8478"
print(Vector3.new(text:match("(.+), (.+), (.+)")))  --> 50.5493011, 75.3234024, 71.8478012

how come it returns more decimals than necessary? how do i make it exact?

2 Likes

That’s just a floating point error, that happens regardless of the string formatting. There’s nothing you can do about it: it’s just how computers store decimals.

3 Likes

If you don’t want to “see” all the decimals, you can print the vector like so:

print(("%.3f, %.3f, %.3f"):format(vec.X, vec.Y. vec.Z))

This will give you a representation that is rounded to three decimal places.

1 Like

This would work:

local StringVector = "50.5493, 75.3234, 71.8478"
local tab = {}
for s in string.gmatch(StringVector,"[^,]+") do
    table.insert(tab,tonumber(s))
end
local NewVector = Vector3.new(unpack(tab))
3 Likes
local function toVector3(String, Separator)
    local Separator = Separator or ','

    local axes = {}

    for axis in String:gmatch('[^'..Separator..']+') do
        axes[#axes + 1] = axis
    end

    return Vector3.new(axes[1], axes[2], axes[3])
end

local newVector = toVector3('50.00, 10.00, 20.00', ', ')

Alternative method could be to tack the function onto the vector sub-section:

local vec_mt = {__index = Vector3)
local Vector3 = {}
setmetatable(Vector3, vec_mt)

Vector3.fromString = function(String, Separator)
    local Separator = Separator or ','

    local axes = {}

    for axis in String:gmatch('[^'..Separator..']+') do
        axes[#axes + 1] = axis
    end

    return Vector3.new(axes[1], axes[2], axes[3])
end

local newVector = Vector3.fromString('50.00, 10.00, 20.00', ', ')

The real question is, why are you trying to convert vectors from string format in the first place?

1 Like