Jump to content

Vector3 to JSON


Sorata_Kanda

Recommended Posts

Posted

Hey everyone,

as far as I know, creating Vector3() is just basically a table containing x, y, z, isn't it? If so, why can't you just use 

toJSON(Vector3())

in order to convert it to JSON so you can store it in a database?

Thanks in advance!

  • Moderators
Posted (edited)

Nope, a vector isn't a table.

I am not exactly sure if they build this data type in C++ or it might be a meta-table. Not that it really matters. As long as you can work with them.

 

Untested converter

do
	local keys = {"x", "y", "z", "w"}
	function vectorToTable (vector) 
		local newTable = {}
		for i=1, #keys do
			local key = keys[i]
			local value = vector[key]
			if value then
				newTable[key] = value
			else
				break
			end
		end
		return newTable
	end
end
iprint(toJSON(vectorToTable(Vector2(234,2434))), "\n\n" , toJSON(vectorToTable(Vector3(234,2434,454))), "\n\n" , toJSON(vectorToTable(Vector4(234,2434,454, 365))) )

 

 

 

 

Edited by IIYAMA
Posted

I did a sort of a "serializer/deserializer" too, but I don't really understand how the concatation on

fromJSON(...)

Following example:

local json = "[\"[123, 1, 3]\"]"
outputDebugString(tostring(fromJSON(json)) -- Delivers [123, 1, 3]
local x, y, z = fromJSON(json) -- Results in nil values

-- But ...
  
for k, v in ipairs(fromJSON(json)) do
	outputDebugString(k .. " " .. v)
    --[[
    Delivers...
       1 123
       2 1
       3 3
    ]]
end
  
-- I also tried this
local jsonTbl = fromJSON(json)
outputDebugString(jsonTbl[1] .. " " .. jsonTbl[2] .. " " .. jsonTbl[3]) -- Results in error due to nil value

On the wiki page, it shows that it's supposed to work like I did with local x, y, z ...

  • Moderators
Posted

@Sorata_Kanda

Example on line 3 shouldn't be working. You need the unpack function for that. (Which unpacks the table)

local x, y, z = unpack(fromJSON(json) )

 

The last example should be working. Hmmm strange.

 

 

Well this is why I use iprint:

iprint(fromJSON(json))

 

I love to know with what I am dealing with.

 

Posted

@IIYAMA

Well, seems like I have fixed it. I think it didn't work out quite well because the kind of formats I used were still saved in my database, thus failing to be parsed wrong.

Oh, and thanks for the tip with iprint. I'll take a look at that.

 

/close

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...