Loading data from JSON.

Hello Facepunch

I’m wondering if anyone could help me with the issue I’m having. I’m doing a little test to see if I can assign a value to a door, and when I restart the server it’ll be still assigned. This is what I currently have.



-- Where we assign the values.

Doors[eid] = {ent=ent,cost=val,renter=false,roomnum=roomnum}

// above is the table we add the values too and we write.

// The values above are added like so, /door (price) (roomid)






-- Below this is where we save our doors.
-- we save the doors doing /savedoor

function saveDoorValuesForMap(ply, arg)
	
	local hSave = util.TableToJSON( Doors ) -- Convert the player table to JSON

	file.Write( "frank_data/hotel_data.txt", hSave ) -- Write to .txt

end





-- Loading the assigned doors.

function loadSavedDoorsValues()
	if !file.Exists( "frank_data/hotel_data.txt", "DATA" ) then
		file.CreateDir( "frank_data" )
	else
		local doorData = util.JSONToTable( file.Read( "frank_data/hotel_data.txt", "DATA" )  )
		
		for k, door in pairs( ents.GetAll() ) do

			door.cost = doorData["cost"]
			k.cost = doorData["cost"]
			
			PrintTable(doorData)
		end
		
	end
end
hook.Add("Initialize", "frank-loadDoor", loadSavedDoorsValues)



Help is much apprecaited, thank you.

To be able to save data for all doors for the map you really should use

Entity:MapCreationID
and

ents.GetMapCreatedEntity
instead of that, not with the entity id, because that can change eventually over time, so instead it would be something like



-- Where we assign the values.

Doors[mapCreationID] = {cost=val,renter=false,roomnum=roomnum}




function loadSavedDoorsValues()
	if !file.Exists( "frank_data/hotel_data.txt", "DATA" ) then
		file.CreateDir( "frank_data" )
	else
		local doorData = util.JSONToTable( file.Read( "frank_data/hotel_data.txt", "DATA" )  )
		
		for mapid, data in pairs(doorData) ) do
			local door = ents.GetMapCreatedEntity(mapid)
			if not IsValid(door) then return end
		
			door.cost = doorData["cost"]
			k.cost = doorData["cost"]
		end
		
	end
end
hook.Add("Initialize", "frank-loadDoor", loadSavedDoorsValues)