]> git.lizzy.rs Git - dragonfireclient.git/blob - builtin/common/misc_helpers.lua
Merge branch 'master' of https://github.com/minetest/minetest
[dragonfireclient.git] / builtin / common / misc_helpers.lua
1 -- Minetest: builtin/misc_helpers.lua
2
3 --------------------------------------------------------------------------------
4 -- Localize functions to avoid table lookups (better performance).
5 local string_sub, string_find = string.sub, string.find
6
7 --------------------------------------------------------------------------------
8 local function basic_dump(o)
9         local tp = type(o)
10         if tp == "number" then
11                 return tostring(o)
12         elseif tp == "string" then
13                 return string.format("%q", o)
14         elseif tp == "boolean" then
15                 return tostring(o)
16         elseif tp == "nil" then
17                 return "nil"
18         -- Uncomment for full function dumping support.
19         -- Not currently enabled because bytecode isn't very human-readable and
20         -- dump's output is intended for humans.
21         --elseif tp == "function" then
22         --      return string.format("loadstring(%q)", string.dump(o))
23         elseif tp == "userdata" then
24                 return tostring(o)
25         else
26                 return string.format("<%s>", tp)
27         end
28 end
29
30 local keywords = {
31         ["and"] = true,
32         ["break"] = true,
33         ["do"] = true,
34         ["else"] = true,
35         ["elseif"] = true,
36         ["end"] = true,
37         ["false"] = true,
38         ["for"] = true,
39         ["function"] = true,
40         ["goto"] = true,  -- Lua 5.2
41         ["if"] = true,
42         ["in"] = true,
43         ["local"] = true,
44         ["nil"] = true,
45         ["not"] = true,
46         ["or"] = true,
47         ["repeat"] = true,
48         ["return"] = true,
49         ["then"] = true,
50         ["true"] = true,
51         ["until"] = true,
52         ["while"] = true,
53 }
54 local function is_valid_identifier(str)
55         if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
56                 return false
57         end
58         return true
59 end
60
61 --------------------------------------------------------------------------------
62 -- Dumps values in a line-per-value format.
63 -- For example, {test = {"Testing..."}} becomes:
64 --   _["test"] = {}
65 --   _["test"][1] = "Testing..."
66 -- This handles tables as keys and circular references properly.
67 -- It also handles multiple references well, writing the table only once.
68 -- The dumped argument is internal-only.
69
70 function dump2(o, name, dumped)
71         name = name or "_"
72         -- "dumped" is used to keep track of serialized tables to handle
73         -- multiple references and circular tables properly.
74         -- It only contains tables as keys.  The value is the name that
75         -- the table has in the dump, eg:
76         -- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
77         dumped = dumped or {}
78         if type(o) ~= "table" then
79                 return string.format("%s = %s\n", name, basic_dump(o))
80         end
81         if dumped[o] then
82                 return string.format("%s = %s\n", name, dumped[o])
83         end
84         dumped[o] = name
85         -- This contains a list of strings to be concatenated later (because
86         -- Lua is slow at individual concatenation).
87         local t = {}
88         for k, v in pairs(o) do
89                 local keyStr
90                 if type(k) == "table" then
91                         if dumped[k] then
92                                 keyStr = dumped[k]
93                         else
94                                 -- Key tables don't have a name, so use one of
95                                 -- the form _G["table: 0xFFFFFFF"]
96                                 keyStr = string.format("_G[%q]", tostring(k))
97                                 -- Dump key table
98                                 t[#t + 1] = dump2(k, keyStr, dumped)
99                         end
100                 else
101                         keyStr = basic_dump(k)
102                 end
103                 local vname = string.format("%s[%s]", name, keyStr)
104                 t[#t + 1] = dump2(v, vname, dumped)
105         end
106         return string.format("%s = {}\n%s", name, table.concat(t))
107 end
108
109 --------------------------------------------------------------------------------
110 -- This dumps values in a one-statement format.
111 -- For example, {test = {"Testing..."}} becomes:
112 -- [[{
113 --      test = {
114 --              "Testing..."
115 --      }
116 -- }]]
117 -- This supports tables as keys, but not circular references.
118 -- It performs poorly with multiple references as it writes out the full
119 -- table each time.
120 -- The indent field specifies a indentation string, it defaults to a tab.
121 -- Use the empty string to disable indentation.
122 -- The dumped and level arguments are internal-only.
123
124 function dump(o, indent, nested, level)
125         local t = type(o)
126         if not level and t == "userdata" then
127                 -- when userdata (e.g. player) is passed directly, print its metatable:
128                 return "userdata metatable: " .. dump(getmetatable(o))
129         end
130         if t ~= "table" then
131                 return basic_dump(o)
132         end
133
134         -- Contains table -> true/nil of currently nested tables
135         nested = nested or {}
136         if nested[o] then
137                 return "<circular reference>"
138         end
139         nested[o] = true
140         indent = indent or "\t"
141         level = level or 1
142
143         local ret = {}
144         local dumped_indexes = {}
145         for i, v in ipairs(o) do
146                 ret[#ret + 1] = dump(v, indent, nested, level + 1)
147                 dumped_indexes[i] = true
148         end
149         for k, v in pairs(o) do
150                 if not dumped_indexes[k] then
151                         if type(k) ~= "string" or not is_valid_identifier(k) then
152                                 k = "["..dump(k, indent, nested, level + 1).."]"
153                         end
154                         v = dump(v, indent, nested, level + 1)
155                         ret[#ret + 1] = k.." = "..v
156                 end
157         end
158         nested[o] = nil
159         if indent ~= "" then
160                 local indent_str = "\n"..string.rep(indent, level)
161                 local end_indent_str = "\n"..string.rep(indent, level - 1)
162                 return string.format("{%s%s%s}",
163                                 indent_str,
164                                 table.concat(ret, ","..indent_str),
165                                 end_indent_str)
166         end
167         return "{"..table.concat(ret, ", ").."}"
168 end
169
170 --------------------------------------------------------------------------------
171 function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
172         delim = delim or ","
173         max_splits = max_splits or -2
174         local items = {}
175         local pos, len = 1, #str
176         local plain = not sep_is_pattern
177         max_splits = max_splits + 1
178         repeat
179                 local np, npe = string_find(str, delim, pos, plain)
180                 np, npe = (np or (len+1)), (npe or (len+1))
181                 if (not np) or (max_splits == 1) then
182                         np = len + 1
183                         npe = np
184                 end
185                 local s = string_sub(str, pos, np - 1)
186                 if include_empty or (s ~= "") then
187                         max_splits = max_splits - 1
188                         items[#items + 1] = s
189                 end
190                 pos = npe + 1
191         until (max_splits == 0) or (pos > (len + 1))
192         return items
193 end
194
195 --------------------------------------------------------------------------------
196 function table.indexof(list, val)
197         for i, v in ipairs(list) do
198                 if v == val then
199                         return i
200                 end
201         end
202         return -1
203 end
204
205 --------------------------------------------------------------------------------
206 function string:trim()
207         return self:match("^%s*(.-)%s*$")
208 end
209
210 --------------------------------------------------------------------------------
211 function math.hypot(x, y)
212         return math.sqrt(x * x + y * y)
213 end
214
215 --------------------------------------------------------------------------------
216 function math.sign(x, tolerance)
217         tolerance = tolerance or 0
218         if x > tolerance then
219                 return 1
220         elseif x < -tolerance then
221                 return -1
222         end
223         return 0
224 end
225
226 --------------------------------------------------------------------------------
227 function math.factorial(x)
228         assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
229         if x >= 171 then
230                 -- 171! is greater than the biggest double, no need to calculate
231                 return math.huge
232         end
233         local v = 1
234         for k = 2, x do
235                 v = v * k
236         end
237         return v
238 end
239
240
241 function math.round(x)
242         if x >= 0 then
243                 return math.floor(x + 0.5)
244         end
245         return math.ceil(x - 0.5)
246 end
247
248 local formspec_escapes = {
249         ["\\"] = "\\\\",
250         ["["] = "\\[",
251         ["]"] = "\\]",
252         [";"] = "\\;",
253         [","] = "\\,"
254 }
255 function core.formspec_escape(text)
256         -- Use explicit character set instead of dot here because it doubles the performance
257         return text and string.gsub(text, "[\\%[%];,]", formspec_escapes)
258 end
259
260
261 function core.wrap_text(text, max_length, as_table)
262         local result = {}
263         local line = {}
264         if #text <= max_length then
265                 return as_table and {text} or text
266         end
267
268         local line_length = 0
269         for word in text:gmatch("%S+") do
270                 if line_length > 0 and line_length + #word + 1 >= max_length then
271                         -- word wouldn't fit on current line, move to next line
272                         table.insert(result, table.concat(line, " "))
273                         line = {word}
274                         line_length = #word
275                 else
276                         table.insert(line, word)
277                         line_length = line_length + 1 + #word
278                 end
279         end
280
281         table.insert(result, table.concat(line, " "))
282         return as_table and result or table.concat(result, "\n")
283 end
284
285 --------------------------------------------------------------------------------
286
287 if INIT == "game" then
288         local dirs1 = {9, 18, 7, 12}
289         local dirs2 = {20, 23, 22, 21}
290
291         function core.rotate_and_place(itemstack, placer, pointed_thing,
292                         infinitestacks, orient_flags, prevent_after_place)
293                 orient_flags = orient_flags or {}
294
295                 local unode = core.get_node_or_nil(pointed_thing.under)
296                 if not unode then
297                         return
298                 end
299                 local undef = core.registered_nodes[unode.name]
300                 local sneaking = placer and placer:get_player_control().sneak
301                 if undef and undef.on_rightclick and not sneaking then
302                         return undef.on_rightclick(pointed_thing.under, unode, placer,
303                                         itemstack, pointed_thing)
304                 end
305                 local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
306
307                 local above = pointed_thing.above
308                 local under = pointed_thing.under
309                 local iswall = (above.y == under.y)
310                 local isceiling = not iswall and (above.y < under.y)
311
312                 if undef and undef.buildable_to then
313                         iswall = false
314                 end
315
316                 if orient_flags.force_floor then
317                         iswall = false
318                         isceiling = false
319                 elseif orient_flags.force_ceiling then
320                         iswall = false
321                         isceiling = true
322                 elseif orient_flags.force_wall then
323                         iswall = true
324                         isceiling = false
325                 elseif orient_flags.invert_wall then
326                         iswall = not iswall
327                 end
328
329                 local param2 = fdir
330                 if iswall then
331                         param2 = dirs1[fdir + 1]
332                 elseif isceiling then
333                         if orient_flags.force_facedir then
334                                 param2 = 20
335                         else
336                                 param2 = dirs2[fdir + 1]
337                         end
338                 else -- place right side up
339                         if orient_flags.force_facedir then
340                                 param2 = 0
341                         end
342                 end
343
344                 local old_itemstack = ItemStack(itemstack)
345                 local new_itemstack = core.item_place_node(itemstack, placer,
346                                 pointed_thing, param2, prevent_after_place)
347                 return infinitestacks and old_itemstack or new_itemstack
348         end
349
350
351 --------------------------------------------------------------------------------
352 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
353 --implies infinite stacks when performing a 6d rotation.
354 --------------------------------------------------------------------------------
355         core.rotate_node = function(itemstack, placer, pointed_thing)
356                 local name = placer and placer:get_player_name() or ""
357                 local invert_wall = placer and placer:get_player_control().sneak or false
358                 return core.rotate_and_place(itemstack, placer, pointed_thing,
359                         core.is_creative_enabled(name),
360                         {invert_wall = invert_wall}, true)
361         end
362 end
363
364 --------------------------------------------------------------------------------
365 function core.explode_table_event(evt)
366         if evt ~= nil then
367                 local parts = evt:split(":")
368                 if #parts == 3 then
369                         local t = parts[1]:trim()
370                         local r = tonumber(parts[2]:trim())
371                         local c = tonumber(parts[3]:trim())
372                         if type(r) == "number" and type(c) == "number"
373                                         and t ~= "INV" then
374                                 return {type=t, row=r, column=c}
375                         end
376                 end
377         end
378         return {type="INV", row=0, column=0}
379 end
380
381 --------------------------------------------------------------------------------
382 function core.explode_textlist_event(evt)
383         if evt ~= nil then
384                 local parts = evt:split(":")
385                 if #parts == 2 then
386                         local t = parts[1]:trim()
387                         local r = tonumber(parts[2]:trim())
388                         if type(r) == "number" and t ~= "INV" then
389                                 return {type=t, index=r}
390                         end
391                 end
392         end
393         return {type="INV", index=0}
394 end
395
396 --------------------------------------------------------------------------------
397 function core.explode_scrollbar_event(evt)
398         local retval = core.explode_textlist_event(evt)
399
400         retval.value = retval.index
401         retval.index = nil
402
403         return retval
404 end
405
406 --------------------------------------------------------------------------------
407 function core.rgba(r, g, b, a)
408         return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
409                         string.format("#%02X%02X%02X", r, g, b)
410 end
411
412 --------------------------------------------------------------------------------
413 function core.pos_to_string(pos, decimal_places)
414         local x = pos.x
415         local y = pos.y
416         local z = pos.z
417         if decimal_places ~= nil then
418                 x = string.format("%." .. decimal_places .. "f", x)
419                 y = string.format("%." .. decimal_places .. "f", y)
420                 z = string.format("%." .. decimal_places .. "f", z)
421         end
422         return "(" .. x .. "," .. y .. "," .. z .. ")"
423 end
424
425 --------------------------------------------------------------------------------
426 function core.string_to_pos(value)
427         if value == nil then
428                 return nil
429         end
430
431         value = value:match("^%((.-)%)$") or value -- strip parentheses
432
433         local x, y, z = value:trim():match("^([%d.-]+)[,%s]%s*([%d.-]+)[,%s]%s*([%d.-]+)$")
434         if x and y and z then
435                 x = tonumber(x)
436                 y = tonumber(y)
437                 z = tonumber(z)
438                 return vector.new(x, y, z)
439         end
440
441         return nil
442 end
443
444
445 --------------------------------------------------------------------------------
446
447 do
448         local rel_num_cap = "(~?-?%d*%.?%d*)" -- may be overly permissive as this will be tonumber'ed anyways
449         local num_delim = "[,%s]%s*"
450         local pattern = "^" .. table.concat({rel_num_cap, rel_num_cap, rel_num_cap}, num_delim) .. "$"
451
452         local function parse_area_string(pos, relative_to)
453                 local pp = {}
454                 pp.x, pp.y, pp.z = pos:trim():match(pattern)
455                 return core.parse_coordinates(pp.x, pp.y, pp.z, relative_to)
456         end
457
458         function core.string_to_area(value, relative_to)
459                 local p1, p2 = value:match("^%((.-)%)%s*%((.-)%)$")
460                 if not p1 then
461                         return
462                 end
463
464                 p1 = parse_area_string(p1, relative_to)
465                 p2 = parse_area_string(p2, relative_to)
466
467                 if p1 == nil or p2 == nil then
468                         return
469                 end
470
471                 return p1, p2
472         end
473 end
474
475 --------------------------------------------------------------------------------
476 function table.copy(t, seen)
477         local n = {}
478         seen = seen or {}
479         seen[t] = n
480         for k, v in pairs(t) do
481                 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
482                         (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
483         end
484         return n
485 end
486
487
488 function table.insert_all(t, other)
489         for i=1, #other do
490                 t[#t + 1] = other[i]
491         end
492         return t
493 end
494
495
496 function table.key_value_swap(t)
497         local ti = {}
498         for k,v in pairs(t) do
499                 ti[v] = k
500         end
501         return ti
502 end
503
504
505 function table.shuffle(t, from, to, random)
506         from = from or 1
507         to = to or #t
508         random = random or math.random
509         local n = to - from + 1
510         while n > 1 do
511                 local r = from + n-1
512                 local l = from + random(0, n-1)
513                 t[l], t[r] = t[r], t[l]
514                 n = n-1
515         end
516 end
517
518
519 function table.combine(t, other)
520         other = other or {}
521         for k, v in pairs(other) do
522                 if type(v) == "table" and type(t[k]) == "table" then
523                         table.combine(t[k], v)
524                 else
525                         t[k] = v
526                 end
527         end
528 end
529
530 --------------------------------------------------------------------------------
531 -- mainmenu only functions
532 --------------------------------------------------------------------------------
533 if INIT == "mainmenu" then
534         function core.get_game(index)
535                 local games = core.get_games()
536
537                 if index > 0 and index <= #games then
538                         return games[index]
539                 end
540
541                 return nil
542         end
543 end
544
545 if core.gettext then -- for client and mainmenu
546         function fgettext_ne(text, ...)
547                 text = core.gettext(text)
548                 local arg = {n=select('#', ...), ...}
549                 if arg.n >= 1 then
550                         -- Insert positional parameters ($1, $2, ...)
551                         local result = ''
552                         local pos = 1
553                         while pos <= text:len() do
554                                 local newpos = text:find('[$]', pos)
555                                 if newpos == nil then
556                                         result = result .. text:sub(pos)
557                                         pos = text:len() + 1
558                                 else
559                                         local paramindex =
560                                                 tonumber(text:sub(newpos+1, newpos+1))
561                                         result = result .. text:sub(pos, newpos-1)
562                                                 .. tostring(arg[paramindex])
563                                         pos = newpos + 2
564                                 end
565                         end
566                         text = result
567                 end
568                 return text
569         end
570
571         function fgettext(text, ...)
572                 return core.formspec_escape(fgettext_ne(text, ...))
573         end
574 end
575
576 local ESCAPE_CHAR = string.char(0x1b)
577
578 function core.get_color_escape_sequence(color)
579         return ESCAPE_CHAR .. "(c@" .. color .. ")"
580 end
581
582 function core.get_background_escape_sequence(color)
583         return ESCAPE_CHAR .. "(b@" .. color .. ")"
584 end
585
586 function core.colorize(color, message)
587         local lines = tostring(message):split("\n", true)
588         local color_code = core.get_color_escape_sequence(color)
589
590         for i, line in ipairs(lines) do
591                 lines[i] = color_code .. line
592         end
593
594         return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
595 end
596
597 local function rgb_to_hex(rgb)
598         local hexadecimal = "#"
599
600         for key, value in pairs(rgb) do
601                 local hex = ""
602
603                 while(value > 0)do
604                         local index = math.fmod(value, 16) + 1
605                         value = math.floor(value / 16)
606                         hex = string.sub("0123456789ABCDEF", index, index) .. hex
607                 end
608
609                 if(string.len(hex) == 0)then
610                         hex = "00"
611                 elseif(string.len(hex) == 1)then
612                         hex = "0" .. hex
613                 end
614
615                 hexadecimal = hexadecimal .. hex
616         end
617
618         return hexadecimal
619 end
620
621 local function color_from_hue(hue)
622         local h = hue / 60
623         local c = 255
624         local x = (1 - math.abs(h % 2 - 1)) * 255
625
626         local i = math.floor(h)
627         if i == 0 then
628                 return rgb_to_hex({c, x, 0})
629         elseif i == 1 then
630                 return rgb_to_hex({x, c, 0})
631         elseif i == 2 then
632                 return rgb_to_hex({0, c, x})
633         elseif i == 3 then
634                 return rgb_to_hex({0, x, c})
635         elseif i == 4 then
636                 return rgb_to_hex({x, 0, c})
637         else
638                 return rgb_to_hex({c, 0, x})
639         end
640 end
641
642 function core.rainbow(input)
643         local step = 360 / input:len()
644         local hue = 0
645         local output = ""
646         for i = 1, input:len() do
647                 local char = input:sub(i, i)
648                 if char:match("%s") then
649                         output = output .. char
650                 else
651                         output = output  .. core.get_color_escape_sequence(color_from_hue(hue)) .. char
652                 end
653                 hue = hue + step
654         end
655         return output
656 end
657
658 function core.strip_foreground_colors(str)
659         return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
660 end
661
662 function core.strip_background_colors(str)
663         return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
664 end
665
666 function core.strip_colors(str)
667         return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
668 end
669
670 function core.translate(textdomain, str, ...)
671         local start_seq
672         if textdomain == "" then
673                 start_seq = ESCAPE_CHAR .. "T"
674         else
675                 start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
676         end
677         local arg = {n=select('#', ...), ...}
678         local end_seq = ESCAPE_CHAR .. "E"
679         local arg_index = 1
680         local translated = str:gsub("@(.)", function(matched)
681                 local c = string.byte(matched)
682                 if string.byte("1") <= c and c <= string.byte("9") then
683                         local a = c - string.byte("0")
684                         if a ~= arg_index then
685                                 error("Escape sequences in string given to core.translate " ..
686                                         "are not in the correct order: got @" .. matched ..
687                                         "but expected @" .. tostring(arg_index))
688                         end
689                         if a > arg.n then
690                                 error("Not enough arguments provided to core.translate")
691                         end
692                         arg_index = arg_index + 1
693                         return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
694                 elseif matched == "n" then
695                         return "\n"
696                 else
697                         return matched
698                 end
699         end)
700         if arg_index < arg.n + 1 then
701                 error("Too many arguments provided to core.translate")
702         end
703         return start_seq .. translated .. end_seq
704 end
705
706 function core.get_translator(textdomain)
707         return function(str, ...) return core.translate(textdomain or "", str, ...) end
708 end
709
710 function core.get_pointed_thing_position(pointed_thing, above)
711         if pointed_thing.type == "node" then
712                 if above then
713                         -- The position where a node would be placed
714                         return pointed_thing.above
715                 end
716                 -- The position where a node would be dug
717                 return pointed_thing.under
718         elseif pointed_thing.type == "object" then
719                 return pointed_thing.ref and pointed_thing.ref:get_pos()
720         end
721 end
722
723 --------------------------------------------------------------------------------
724 -- Returns the exact coordinate of a pointed surface
725 --------------------------------------------------------------------------------
726 function core.pointed_thing_to_face_pos(placer, pointed_thing)
727         -- Avoid crash in some situations when player is inside a node, causing
728         -- 'above' to equal 'under'.
729         if vector.equals(pointed_thing.above, pointed_thing.under) then
730                 return pointed_thing.under
731         end
732
733         local eye_height = placer:get_properties().eye_height
734         local eye_offset_first = placer:get_eye_offset()
735         local node_pos = pointed_thing.under
736         local camera_pos = placer:get_pos()
737         local pos_off = vector.multiply(
738                         vector.subtract(pointed_thing.above, node_pos), 0.5)
739         local look_dir = placer:get_look_dir()
740         local offset, nc
741         local oc = {}
742
743         for c, v in pairs(pos_off) do
744                 if nc or v == 0 then
745                         oc[#oc + 1] = c
746                 else
747                         offset = v
748                         nc = c
749                 end
750         end
751
752         local fine_pos = {[nc] = node_pos[nc] + offset}
753         camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
754         local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
755
756         for i = 1, #oc do
757                 fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
758         end
759         return fine_pos
760 end
761
762 function core.string_to_privs(str, delim)
763         assert(type(str) == "string")
764         delim = delim or ','
765         local privs = {}
766         for _, priv in pairs(string.split(str, delim)) do
767                 privs[priv:trim()] = true
768         end
769         return privs
770 end
771
772 function core.privs_to_string(privs, delim)
773         assert(type(privs) == "table")
774         delim = delim or ','
775         local list = {}
776         for priv, bool in pairs(privs) do
777                 if bool then
778                         list[#list + 1] = priv
779                 end
780         end
781         return table.concat(list, delim)
782 end
783
784 function core.is_nan(number)
785         return number ~= number
786 end
787
788 --[[ Helper function for parsing an optionally relative number
789 of a chat command parameter, using the chat command tilde notation.
790
791 Parameters:
792 * arg: String snippet containing the number; possible values:
793     * "<number>": return as number
794     * "~<number>": return relative_to + <number>
795     * "~": return relative_to
796     * Anything else will return `nil`
797 * relative_to: Number to which the `arg` number might be relative to
798
799 Returns:
800 A number or `nil`, depending on `arg.
801
802 Examples:
803 * `core.parse_relative_number("5", 10)` returns 5
804 * `core.parse_relative_number("~5", 10)` returns 15
805 * `core.parse_relative_number("~", 10)` returns 10
806 ]]
807 function core.parse_relative_number(arg, relative_to)
808         if not arg then
809                 return nil
810         elseif arg == "~" then
811                 return relative_to
812         elseif string.sub(arg, 1, 1) == "~" then
813                 local number = tonumber(string.sub(arg, 2))
814                 if not number then
815                         return nil
816                 end
817                 if core.is_nan(number) or number == math.huge or number == -math.huge then
818                         return nil
819                 end
820                 return relative_to + number
821         else
822                 local number = tonumber(arg)
823                 if core.is_nan(number) or number == math.huge or number == -math.huge then
824                         return nil
825                 end
826                 return number
827         end
828 end
829
830 --[[ Helper function to parse coordinates that might be relative
831 to another position; supports chat command tilde notation.
832 Intended to be used in chat command parameter parsing.
833
834 Parameters:
835 * x, y, z: Parsed x, y, and z coordinates as strings
836 * relative_to: Position to which to compare the position
837
838 Syntax of x, y and z:
839 * "<number>": return as number
840 * "~<number>": return <number> + player position on this axis
841 * "~": return player position on this axis
842
843 Returns: a vector or nil for invalid input or if player does not exist
844 ]]
845 function core.parse_coordinates(x, y, z, relative_to)
846         if not relative_to then
847                 x, y, z = tonumber(x), tonumber(y), tonumber(z)
848                 return x and y and z and { x = x, y = y, z = z }
849         end
850         local rx = core.parse_relative_number(x, relative_to.x)
851         local ry = core.parse_relative_number(y, relative_to.y)
852         local rz = core.parse_relative_number(z, relative_to.z)
853         return rx and ry and rz and { x = rx, y = ry, z = rz }
854 end
855
856 function core.inventorycube(img1, img2, img3)
857         img2 = img2 or img1
858         img3 = img3 or img1
859         return "[inventorycube"
860                         .. "{" .. img1:gsub("%^", "&")
861                         .. "{" .. img2:gsub("%^", "&")
862                         .. "{" .. img3:gsub("%^", "&")
863 end