]> git.lizzy.rs Git - minetest.git/blob - builtin/common/misc_helpers.lua
Error when string.split is given empty separator (#13132)
[minetest.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         if delim == "" then
174                 error("string.split separator is empty", 2)
175         end
176         max_splits = max_splits or -2
177         local items = {}
178         local pos, len = 1, #str
179         local plain = not sep_is_pattern
180         max_splits = max_splits + 1
181         repeat
182                 local np, npe = string_find(str, delim, pos, plain)
183                 np, npe = (np or (len+1)), (npe or (len+1))
184                 if (not np) or (max_splits == 1) then
185                         np = len + 1
186                         npe = np
187                 end
188                 local s = string_sub(str, pos, np - 1)
189                 if include_empty or (s ~= "") then
190                         max_splits = max_splits - 1
191                         items[#items + 1] = s
192                 end
193                 pos = npe + 1
194         until (max_splits == 0) or (pos > (len + 1))
195         return items
196 end
197
198 --------------------------------------------------------------------------------
199 function table.indexof(list, val)
200         for i, v in ipairs(list) do
201                 if v == val then
202                         return i
203                 end
204         end
205         return -1
206 end
207
208 --------------------------------------------------------------------------------
209 function string:trim()
210         return self:match("^%s*(.-)%s*$")
211 end
212
213 --------------------------------------------------------------------------------
214 function math.hypot(x, y)
215         return math.sqrt(x * x + y * y)
216 end
217
218 --------------------------------------------------------------------------------
219 function math.sign(x, tolerance)
220         tolerance = tolerance or 0
221         if x > tolerance then
222                 return 1
223         elseif x < -tolerance then
224                 return -1
225         end
226         return 0
227 end
228
229 --------------------------------------------------------------------------------
230 function math.factorial(x)
231         assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
232         if x >= 171 then
233                 -- 171! is greater than the biggest double, no need to calculate
234                 return math.huge
235         end
236         local v = 1
237         for k = 2, x do
238                 v = v * k
239         end
240         return v
241 end
242
243
244 function math.round(x)
245         if x >= 0 then
246                 return math.floor(x + 0.5)
247         end
248         return math.ceil(x - 0.5)
249 end
250
251 local formspec_escapes = {
252         ["\\"] = "\\\\",
253         ["["] = "\\[",
254         ["]"] = "\\]",
255         [";"] = "\\;",
256         [","] = "\\,",
257         ["$"] = "\\$",
258 }
259 function core.formspec_escape(text)
260         -- Use explicit character set instead of dot here because it doubles the performance
261         return text and string.gsub(text, "[\\%[%];,$]", formspec_escapes)
262 end
263
264
265 function core.wrap_text(text, max_length, as_table)
266         local result = {}
267         local line = {}
268         if #text <= max_length then
269                 return as_table and {text} or text
270         end
271
272         local line_length = 0
273         for word in text:gmatch("%S+") do
274                 if line_length > 0 and line_length + #word + 1 >= max_length then
275                         -- word wouldn't fit on current line, move to next line
276                         table.insert(result, table.concat(line, " "))
277                         line = {word}
278                         line_length = #word
279                 else
280                         table.insert(line, word)
281                         line_length = line_length + 1 + #word
282                 end
283         end
284
285         table.insert(result, table.concat(line, " "))
286         return as_table and result or table.concat(result, "\n")
287 end
288
289 --------------------------------------------------------------------------------
290
291 if INIT == "game" then
292         local dirs1 = {9, 18, 7, 12}
293         local dirs2 = {20, 23, 22, 21}
294
295         function core.rotate_and_place(itemstack, placer, pointed_thing,
296                         infinitestacks, orient_flags, prevent_after_place)
297                 orient_flags = orient_flags or {}
298
299                 local unode = core.get_node_or_nil(pointed_thing.under)
300                 if not unode then
301                         return
302                 end
303                 local undef = core.registered_nodes[unode.name]
304                 local sneaking = placer and placer:get_player_control().sneak
305                 if undef and undef.on_rightclick and not sneaking then
306                         return undef.on_rightclick(pointed_thing.under, unode, placer,
307                                         itemstack, pointed_thing)
308                 end
309                 local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
310
311                 local above = pointed_thing.above
312                 local under = pointed_thing.under
313                 local iswall = (above.y == under.y)
314                 local isceiling = not iswall and (above.y < under.y)
315
316                 if undef and undef.buildable_to then
317                         iswall = false
318                 end
319
320                 if orient_flags.force_floor then
321                         iswall = false
322                         isceiling = false
323                 elseif orient_flags.force_ceiling then
324                         iswall = false
325                         isceiling = true
326                 elseif orient_flags.force_wall then
327                         iswall = true
328                         isceiling = false
329                 elseif orient_flags.invert_wall then
330                         iswall = not iswall
331                 end
332
333                 local param2 = fdir
334                 if iswall then
335                         param2 = dirs1[fdir + 1]
336                 elseif isceiling then
337                         if orient_flags.force_facedir then
338                                 param2 = 20
339                         else
340                                 param2 = dirs2[fdir + 1]
341                         end
342                 else -- place right side up
343                         if orient_flags.force_facedir then
344                                 param2 = 0
345                         end
346                 end
347
348                 local old_itemstack = ItemStack(itemstack)
349                 local new_itemstack = core.item_place_node(itemstack, placer,
350                                 pointed_thing, param2, prevent_after_place)
351                 return infinitestacks and old_itemstack or new_itemstack
352         end
353
354
355 --------------------------------------------------------------------------------
356 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
357 --implies infinite stacks when performing a 6d rotation.
358 --------------------------------------------------------------------------------
359         core.rotate_node = function(itemstack, placer, pointed_thing)
360                 local name = placer and placer:get_player_name() or ""
361                 local invert_wall = placer and placer:get_player_control().sneak or false
362                 return core.rotate_and_place(itemstack, placer, pointed_thing,
363                         core.is_creative_enabled(name),
364                         {invert_wall = invert_wall}, true)
365         end
366 end
367
368 --------------------------------------------------------------------------------
369 function core.explode_table_event(evt)
370         if evt ~= nil then
371                 local parts = evt:split(":")
372                 if #parts == 3 then
373                         local t = parts[1]:trim()
374                         local r = tonumber(parts[2]:trim())
375                         local c = tonumber(parts[3]:trim())
376                         if type(r) == "number" and type(c) == "number"
377                                         and t ~= "INV" then
378                                 return {type=t, row=r, column=c}
379                         end
380                 end
381         end
382         return {type="INV", row=0, column=0}
383 end
384
385 --------------------------------------------------------------------------------
386 function core.explode_textlist_event(evt)
387         if evt ~= nil then
388                 local parts = evt:split(":")
389                 if #parts == 2 then
390                         local t = parts[1]:trim()
391                         local r = tonumber(parts[2]:trim())
392                         if type(r) == "number" and t ~= "INV" then
393                                 return {type=t, index=r}
394                         end
395                 end
396         end
397         return {type="INV", index=0}
398 end
399
400 --------------------------------------------------------------------------------
401 function core.explode_scrollbar_event(evt)
402         local retval = core.explode_textlist_event(evt)
403
404         retval.value = retval.index
405         retval.index = nil
406
407         return retval
408 end
409
410 --------------------------------------------------------------------------------
411 function core.rgba(r, g, b, a)
412         return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
413                         string.format("#%02X%02X%02X", r, g, b)
414 end
415
416 --------------------------------------------------------------------------------
417 function core.pos_to_string(pos, decimal_places)
418         local x = pos.x
419         local y = pos.y
420         local z = pos.z
421         if decimal_places ~= nil then
422                 x = string.format("%." .. decimal_places .. "f", x)
423                 y = string.format("%." .. decimal_places .. "f", y)
424                 z = string.format("%." .. decimal_places .. "f", z)
425         end
426         return "(" .. x .. "," .. y .. "," .. z .. ")"
427 end
428
429 --------------------------------------------------------------------------------
430 function core.string_to_pos(value)
431         if value == nil then
432                 return nil
433         end
434
435         value = value:match("^%((.-)%)$") or value -- strip parentheses
436
437         local x, y, z = value:trim():match("^([%d.-]+)[,%s]%s*([%d.-]+)[,%s]%s*([%d.-]+)$")
438         if x and y and z then
439                 x = tonumber(x)
440                 y = tonumber(y)
441                 z = tonumber(z)
442                 return vector.new(x, y, z)
443         end
444
445         return nil
446 end
447
448
449 --------------------------------------------------------------------------------
450
451 do
452         local rel_num_cap = "(~?-?%d*%.?%d*)" -- may be overly permissive as this will be tonumber'ed anyways
453         local num_delim = "[,%s]%s*"
454         local pattern = "^" .. table.concat({rel_num_cap, rel_num_cap, rel_num_cap}, num_delim) .. "$"
455
456         local function parse_area_string(pos, relative_to)
457                 local pp = {}
458                 pp.x, pp.y, pp.z = pos:trim():match(pattern)
459                 return core.parse_coordinates(pp.x, pp.y, pp.z, relative_to)
460         end
461
462         function core.string_to_area(value, relative_to)
463                 local p1, p2 = value:match("^%((.-)%)%s*%((.-)%)$")
464                 if not p1 then
465                         return
466                 end
467
468                 p1 = parse_area_string(p1, relative_to)
469                 p2 = parse_area_string(p2, relative_to)
470
471                 if p1 == nil or p2 == nil then
472                         return
473                 end
474
475                 return p1, p2
476         end
477 end
478
479 --------------------------------------------------------------------------------
480 function table.copy(t, seen)
481         local n = {}
482         seen = seen or {}
483         seen[t] = n
484         for k, v in pairs(t) do
485                 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
486                         (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
487         end
488         return n
489 end
490
491
492 function table.insert_all(t, other)
493         for i=1, #other do
494                 t[#t + 1] = other[i]
495         end
496         return t
497 end
498
499
500 function table.key_value_swap(t)
501         local ti = {}
502         for k,v in pairs(t) do
503                 ti[v] = k
504         end
505         return ti
506 end
507
508
509 function table.shuffle(t, from, to, random)
510         from = from or 1
511         to = to or #t
512         random = random or math.random
513         local n = to - from + 1
514         while n > 1 do
515                 local r = from + n-1
516                 local l = from + random(0, n-1)
517                 t[l], t[r] = t[r], t[l]
518                 n = n-1
519         end
520 end
521
522
523 --------------------------------------------------------------------------------
524 -- mainmenu only functions
525 --------------------------------------------------------------------------------
526 if core.gettext then -- for client and mainmenu
527         function fgettext_ne(text, ...)
528                 text = core.gettext(text)
529                 local arg = {n=select('#', ...), ...}
530                 if arg.n >= 1 then
531                         -- Insert positional parameters ($1, $2, ...)
532                         local result = ''
533                         local pos = 1
534                         while pos <= text:len() do
535                                 local newpos = text:find('[$]', pos)
536                                 if newpos == nil then
537                                         result = result .. text:sub(pos)
538                                         pos = text:len() + 1
539                                 else
540                                         local paramindex =
541                                                 tonumber(text:sub(newpos+1, newpos+1))
542                                         result = result .. text:sub(pos, newpos-1)
543                                                 .. tostring(arg[paramindex])
544                                         pos = newpos + 2
545                                 end
546                         end
547                         text = result
548                 end
549                 return text
550         end
551
552         function fgettext(text, ...)
553                 return core.formspec_escape(fgettext_ne(text, ...))
554         end
555 end
556
557 local ESCAPE_CHAR = string.char(0x1b)
558
559 function core.get_color_escape_sequence(color)
560         return ESCAPE_CHAR .. "(c@" .. color .. ")"
561 end
562
563 function core.get_background_escape_sequence(color)
564         return ESCAPE_CHAR .. "(b@" .. color .. ")"
565 end
566
567 function core.colorize(color, message)
568         local lines = tostring(message):split("\n", true)
569         local color_code = core.get_color_escape_sequence(color)
570
571         for i, line in ipairs(lines) do
572                 lines[i] = color_code .. line
573         end
574
575         return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
576 end
577
578
579 function core.strip_foreground_colors(str)
580         return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
581 end
582
583 function core.strip_background_colors(str)
584         return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
585 end
586
587 function core.strip_colors(str)
588         return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
589 end
590
591 function core.translate(textdomain, str, ...)
592         local start_seq
593         if textdomain == "" then
594                 start_seq = ESCAPE_CHAR .. "T"
595         else
596                 start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
597         end
598         local arg = {n=select('#', ...), ...}
599         local end_seq = ESCAPE_CHAR .. "E"
600         local arg_index = 1
601         local translated = str:gsub("@(.)", function(matched)
602                 local c = string.byte(matched)
603                 if string.byte("1") <= c and c <= string.byte("9") then
604                         local a = c - string.byte("0")
605                         if a ~= arg_index then
606                                 error("Escape sequences in string given to core.translate " ..
607                                         "are not in the correct order: got @" .. matched ..
608                                         "but expected @" .. tostring(arg_index))
609                         end
610                         if a > arg.n then
611                                 error("Not enough arguments provided to core.translate")
612                         end
613                         arg_index = arg_index + 1
614                         return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
615                 elseif matched == "n" then
616                         return "\n"
617                 else
618                         return matched
619                 end
620         end)
621         if arg_index < arg.n + 1 then
622                 error("Too many arguments provided to core.translate")
623         end
624         return start_seq .. translated .. end_seq
625 end
626
627 function core.get_translator(textdomain)
628         return function(str, ...) return core.translate(textdomain or "", str, ...) end
629 end
630
631 --------------------------------------------------------------------------------
632 -- Returns the exact coordinate of a pointed surface
633 --------------------------------------------------------------------------------
634 function core.pointed_thing_to_face_pos(placer, pointed_thing)
635         -- Avoid crash in some situations when player is inside a node, causing
636         -- 'above' to equal 'under'.
637         if vector.equals(pointed_thing.above, pointed_thing.under) then
638                 return pointed_thing.under
639         end
640
641         local eye_height = placer:get_properties().eye_height
642         local eye_offset_first = placer:get_eye_offset()
643         local node_pos = pointed_thing.under
644         local camera_pos = placer:get_pos()
645         local pos_off = vector.multiply(
646                         vector.subtract(pointed_thing.above, node_pos), 0.5)
647         local look_dir = placer:get_look_dir()
648         local offset, nc
649         local oc = {}
650
651         for c, v in pairs(pos_off) do
652                 if nc or v == 0 then
653                         oc[#oc + 1] = c
654                 else
655                         offset = v
656                         nc = c
657                 end
658         end
659
660         local fine_pos = {[nc] = node_pos[nc] + offset}
661         camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
662         local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
663
664         for i = 1, #oc do
665                 fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
666         end
667         return fine_pos
668 end
669
670 function core.string_to_privs(str, delim)
671         assert(type(str) == "string")
672         delim = delim or ','
673         local privs = {}
674         for _, priv in pairs(string.split(str, delim)) do
675                 privs[priv:trim()] = true
676         end
677         return privs
678 end
679
680 function core.privs_to_string(privs, delim)
681         assert(type(privs) == "table")
682         delim = delim or ','
683         local list = {}
684         for priv, bool in pairs(privs) do
685                 if bool then
686                         list[#list + 1] = priv
687                 end
688         end
689         return table.concat(list, delim)
690 end
691
692 function core.is_nan(number)
693         return number ~= number
694 end
695
696 --[[ Helper function for parsing an optionally relative number
697 of a chat command parameter, using the chat command tilde notation.
698
699 Parameters:
700 * arg: String snippet containing the number; possible values:
701     * "<number>": return as number
702     * "~<number>": return relative_to + <number>
703     * "~": return relative_to
704     * Anything else will return `nil`
705 * relative_to: Number to which the `arg` number might be relative to
706
707 Returns:
708 A number or `nil`, depending on `arg.
709
710 Examples:
711 * `core.parse_relative_number("5", 10)` returns 5
712 * `core.parse_relative_number("~5", 10)` returns 15
713 * `core.parse_relative_number("~", 10)` returns 10
714 ]]
715 function core.parse_relative_number(arg, relative_to)
716         if not arg then
717                 return nil
718         elseif arg == "~" then
719                 return relative_to
720         elseif string.sub(arg, 1, 1) == "~" then
721                 local number = tonumber(string.sub(arg, 2))
722                 if not number then
723                         return nil
724                 end
725                 if core.is_nan(number) or number == math.huge or number == -math.huge then
726                         return nil
727                 end
728                 return relative_to + number
729         else
730                 local number = tonumber(arg)
731                 if core.is_nan(number) or number == math.huge or number == -math.huge then
732                         return nil
733                 end
734                 return number
735         end
736 end
737
738 --[[ Helper function to parse coordinates that might be relative
739 to another position; supports chat command tilde notation.
740 Intended to be used in chat command parameter parsing.
741
742 Parameters:
743 * x, y, z: Parsed x, y, and z coordinates as strings
744 * relative_to: Position to which to compare the position
745
746 Syntax of x, y and z:
747 * "<number>": return as number
748 * "~<number>": return <number> + player position on this axis
749 * "~": return player position on this axis
750
751 Returns: a vector or nil for invalid input or if player does not exist
752 ]]
753 function core.parse_coordinates(x, y, z, relative_to)
754         if not relative_to then
755                 x, y, z = tonumber(x), tonumber(y), tonumber(z)
756                 return x and y and z and { x = x, y = y, z = z }
757         end
758         local rx = core.parse_relative_number(x, relative_to.x)
759         local ry = core.parse_relative_number(y, relative_to.y)
760         local rz = core.parse_relative_number(z, relative_to.z)
761         return rx and ry and rz and { x = rx, y = ry, z = rz }
762 end