-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstates.lua
101 lines (89 loc) · 2.51 KB
/
states.lua
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
log_error, log_warn = dofile(tasks.path .. "/helper_functions.lua")
local function serialize(state_table)
local state_string = ""
for _, s in ipairs(state_table) do
if #state_string > 0 then
state_string = state_string .. ";"
end
state_string = state_string .. s
end
return state_string
end
local function deserialize(state_string)
local state_table = {}
for s in string.gmatch(state_string, "([^;]+)") do
table.insert(state_table, s:trim())
end
return state_table
end
function tasks.get_player_tasks(player)
return core.deserialize(player:get_meta():get_string("tasks")) or {}
end
function tasks.get_player_state(player, id, index)
if type(index) ~= "number" then
index = 0
end
local list = index == true
local player_tasks = tasks.get_player_tasks(player)
local state_string = player_tasks[id]
if index > 0 and state_string ~= nil then
-- return value of single state index
return deserialize(state_string)[index]
end
-- return value of all indexes
if list then
return deserialize(state_string)
end
return state_string
end
function tasks.set_player_state(player, id, index, value)
if value == nil then
value = index
index = 0
end
if value ~= nil then
value = tostring(value):trim()
end
if index > 0 and value == nil then
-- use empty string to preserve indexes
value = ""
end
local player_tasks = tasks.get_player_tasks(player)
local state_string = player_tasks[id]
if index > 0 then
-- update a single index
local state_table = deserialize(state_string or "")
state_table[index] = value
state_string = serialize(state_table)
else
-- overwrite all task data
state_string = value
end
player_tasks[id] = state_string
player:get_meta():set_string("tasks", core.serialize(player_tasks))
local task_def = tasks.get_definition(id)
if task_def == nil then
log_warn("`tasks.set_state`: unregistered ID \"" .. id .. "\"")
elseif tasks.player_is_complete(player, id) then
task_def:on_complete(player)
end
end
function tasks.player_has(player, id)
return tasks.get_player_tasks(player)[id] ~= nil
end
function tasks.player_is_complete(player, id)
local task_def = tasks.get_definition(id)
if task_def == nil then
log_warn("`tasks.player_is_complete`: unregistered ID " .. id)
return false
end
return task_def:is_complete(player) or false
end
function tasks.get_player_log(player, id)
local task_def = tasks.get_definition(id)
if task_def == nil then
log_warn("`tasks.get_player_log`: unregistered ID " .. id)
return false
end
return task_def:get_log(player) or {}
end