aboutsummaryrefslogtreecommitdiff
path: root/gamemode/core/database/sv_queries.lua
blob: 96908d4f7ef63d238e566b8eb8b54f522b83c1f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
---Helper functions for saveing and loading players.
-- Defines functions for saveing/loading the player
--@server sv_queries.lua
--@alias q

local fn = nrequire("utility/fn.lua")
local track = nrequire("core/inventory/sv_invtracker.lua")
local log = nrequire("log.lua")
local q = {}

---Creats a string representation of a player.
-- The string can be used to re-create the player's data with teh deserialize_player function
--@tparam player ply The player to serialize
function q.serialize_player(ply)
	if not IsValid(ply) and ply.data and ply.data.inventories then return "" end
	local sdata = {}
	local invs = {}
	for k,v in pairs(ply.data.inventories) do
		local idata = string.format("%q",v:Serialize())
		invs[k] = {v.Name,string.sub(idata,2,#idata-1)} --remove the otter quotes
	end
	sdata.inventories = invs
	sdata.skills = ply.data.skills
	sdata.quests = ply.data.quests
	sdata.prayers = ply.data.prayers
	sdata.credits = ply.data.credits
	local ret = util.TableToJSON(sdata)
	return ret
end

---Loads a player from a serialized string.
-- Loads a player's data form the string given. The string can be created with the serialize_player() function
--@tparam player ply The player to load data for
--@tparam string str The string representation of the data
function q.deserialize_player(ply,str)
	log.debug("Deserializing player's data : " .. ply:Nick() .. "\n" .. str)
	track.ClearInventories(ply)
	ply.data = ply.data or {}
	ply.data.inventories = ply.data.inventories or {}
	local tbl = util.JSONToTable(str)
	if not tbl then
		log.error("Failed to deserialize player " .. ply:Nick() .. "\n" .. str)
	end
	local invs = tbl.inventories
	for k,v in pairs(invs) do
		track.GiveInventoryWithData(ply,v[1],v[2])
	end
	ply.data.skills = tbl.skills or {}
	ply.data.quests = tbl.quests or {}
	ply.data.credits = tbl.credits or 100
	track.SendPlayerData(ply)
end

---Formats for an sql query.
-- Kind of like string.format, but arguments are pasesd through SQL sanitization ![Requires admin](./req_admin)
--@tparam string fmt The string.format function
--@tparam varargs ... The parameters to format the string with
function q.s_fmt(fmt,...)
	local args = {...}
	fn.map(args,MySQLite.SQLStr)
	return string.format(fmt,unpack(args))
end

return q