summaryrefslogtreecommitdiffstats
path: root/crawl-ref/source/dat/clua/luamark.lua
blob: cc677f18c1b4fa2709337fa53f19f2b3517082fa (plain) (blame)
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
------------------------------------------------------------------------------
-- luamark.lua:
-- Lua map marker handling.
------------------------------------------------------------------------------

dofile('clua/lm_pdesc.lua')
dofile('clua/lm_1way.lua')
dofile('clua/lm_timed.lua')
dofile('clua/lm_flags.lua')
dofile('clua/lm_fog.lua')

function dlua_marker_function(table, name)
  return table[name]
end

function dlua_marker_method(table, name, marker, ...)
  if table[name] then
    return table[name](table, marker, ...)
  end
end

function dlua_marker_read(fn, marker, th)
  return fn({ }, marker, th)
end

lmark = { }

-- Marshalls a table comprising of keys that are strings or numbers only,
-- and values that are strings, numbers, functions, or tables only. The table
-- cannot have cycles, and the table's metatable is not preserved.
function lmark.marshall_table(th, table)
  if not table then
    file.marshall(th, -1)
    return
  end

  -- Count the number of elements first (ugh)
  local nsize = 0
  local tsize = 0
  for _, v in pairs(table) do
    if type(v) == 'table' then
      tsize = tsize + 1
    else
      nsize = nsize + 1
    end
  end

  file.marshall(th, nsize)
  for key, value in pairs(table) do
    if type(value) ~= 'table' then
      file.marshall_meta(th, key)
      file.marshall_meta(th, value)
    end
  end

  file.marshall(th, tsize)
  for key, value in pairs(table) do
    if type(value) == 'table' then
      file.marshall_meta(th, key)
      lmark.marshall_table(th, value)
    end
  end
end

-- Unmarshals a table marshaled by marshall_table.
function lmark.unmarshall_table(th)
  local nsize = file.unmarshall_number(th)

  if nsize == -1 then
    return nil
  end

  local ret = { }
  for i = 1, nsize do
    local key = file.unmarshall_meta(th)
    local val = file.unmarshall_meta(th)
    ret[key] = val
  end

  local tsize = file.unmarshall_number(th)
  for i = 1, tsize do
    local key = file.unmarshall_meta(th)
    local val = lmark.unmarshall_table(th)
    ret[key] = val
  end
  return ret
end