1 -- Minetest: builtin/misc_helpers.lua
3 --------------------------------------------------------------------------------
4 -- Localize functions to avoid table lookups (better performance).
5 local string_sub, string_find = string.sub, string.find
7 --------------------------------------------------------------------------------
8 local function basic_dump(o)
10 if tp == "number" then
12 elseif tp == "string" then
13 return string.format("%q", o)
14 elseif tp == "boolean" then
16 elseif tp == "nil" then
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
26 return string.format("<%s>", tp)
40 ["goto"] = true, -- Lua 5.2
54 local function is_valid_identifier(str)
55 if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
61 --------------------------------------------------------------------------------
62 -- Dumps values in a line-per-value format.
63 -- For example, {test = {"Testing..."}} becomes:
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.
70 function dump2(o, name, dumped)
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"]'
78 if type(o) ~= "table" then
79 return string.format("%s = %s\n", name, basic_dump(o))
82 return string.format("%s = %s\n", name, dumped[o])
85 -- This contains a list of strings to be concatenated later (because
86 -- Lua is slow at individual concatenation).
88 for k, v in pairs(o) do
90 if type(k) == "table" then
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))
98 t[#t + 1] = dump2(k, keyStr, dumped)
101 keyStr = basic_dump(k)
103 local vname = string.format("%s[%s]", name, keyStr)
104 t[#t + 1] = dump2(v, vname, dumped)
106 return string.format("%s = {}\n%s", name, table.concat(t))
109 --------------------------------------------------------------------------------
110 -- This dumps values in a one-statement format.
111 -- For example, {test = {"Testing..."}} becomes:
117 -- This supports tables as keys, but not circular references.
118 -- It performs poorly with multiple references as it writes out the full
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.
124 function dump(o, indent, nested, level)
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))
134 -- Contains table -> true/nil of currently nested tables
135 nested = nested or {}
137 return "<circular reference>"
140 indent = indent or "\t"
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
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).."]"
154 v = dump(v, indent, nested, level + 1)
155 ret[#ret + 1] = k.." = "..v
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}",
164 table.concat(ret, ","..indent_str),
167 return "{"..table.concat(ret, ", ").."}"
170 --------------------------------------------------------------------------------
171 function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
173 max_splits = max_splits or -2
175 local pos, len = 1, #str
176 local plain = not sep_is_pattern
177 max_splits = max_splits + 1
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
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
191 until (max_splits == 0) or (pos > (len + 1))
195 --------------------------------------------------------------------------------
196 function table.indexof(list, val)
197 for i, v in ipairs(list) do
205 --------------------------------------------------------------------------------
206 function string:trim()
207 return self:match("^%s*(.-)%s*$")
210 --------------------------------------------------------------------------------
211 function math.hypot(x, y)
212 return math.sqrt(x * x + y * y)
215 --------------------------------------------------------------------------------
216 function math.sign(x, tolerance)
217 tolerance = tolerance or 0
218 if x > tolerance then
220 elseif x < -tolerance then
226 --------------------------------------------------------------------------------
227 function math.factorial(x)
228 assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
230 -- 171! is greater than the biggest double, no need to calculate
241 function math.round(x)
243 return math.floor(x + 0.5)
245 return math.ceil(x - 0.5)
248 local formspec_escapes = {
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)
261 function core.wrap_text(text, max_length, as_table)
264 if #text <= max_length then
265 return as_table and {text} or text
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, " "))
276 table.insert(line, word)
277 line_length = line_length + 1 + #word
281 table.insert(result, table.concat(line, " "))
282 return as_table and result or table.concat(result, "\n")
285 --------------------------------------------------------------------------------
287 if INIT == "game" then
288 local dirs1 = {9, 18, 7, 12}
289 local dirs2 = {20, 23, 22, 21}
291 function core.rotate_and_place(itemstack, placer, pointed_thing,
292 infinitestacks, orient_flags, prevent_after_place)
293 orient_flags = orient_flags or {}
295 local unode = core.get_node_or_nil(pointed_thing.under)
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)
305 local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
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)
312 if undef and undef.buildable_to then
316 if orient_flags.force_floor then
319 elseif orient_flags.force_ceiling then
322 elseif orient_flags.force_wall then
325 elseif orient_flags.invert_wall then
331 param2 = dirs1[fdir + 1]
332 elseif isceiling then
333 if orient_flags.force_facedir then
336 param2 = dirs2[fdir + 1]
338 else -- place right side up
339 if orient_flags.force_facedir then
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
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)
364 --------------------------------------------------------------------------------
365 function core.explode_table_event(evt)
367 local parts = evt:split(":")
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"
374 return {type=t, row=r, column=c}
378 return {type="INV", row=0, column=0}
381 --------------------------------------------------------------------------------
382 function core.explode_textlist_event(evt)
384 local parts = evt:split(":")
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}
393 return {type="INV", index=0}
396 --------------------------------------------------------------------------------
397 function core.explode_scrollbar_event(evt)
398 local retval = core.explode_textlist_event(evt)
400 retval.value = retval.index
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)
412 --------------------------------------------------------------------------------
413 function core.pos_to_string(pos, decimal_places)
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)
422 return "(" .. x .. "," .. y .. "," .. z .. ")"
425 --------------------------------------------------------------------------------
426 function core.string_to_pos(value)
431 value = value:match("^%((.-)%)$") or value -- strip parentheses
433 local x, y, z = value:trim():match("^([%d.-]+)[,%s]%s*([%d.-]+)[,%s]%s*([%d.-]+)$")
434 if x and y and z then
438 return vector.new(x, y, z)
445 --------------------------------------------------------------------------------
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) .. "$"
452 local function parse_area_string(pos, relative_to)
454 pp.x, pp.y, pp.z = pos:trim():match(pattern)
455 return core.parse_coordinates(pp.x, pp.y, pp.z, relative_to)
458 function core.string_to_area(value, relative_to)
459 local p1, p2 = value:match("^%((.-)%)%s*%((.-)%)$")
464 p1 = parse_area_string(p1, relative_to)
465 p2 = parse_area_string(p2, relative_to)
467 if p1 == nil or p2 == nil then
475 --------------------------------------------------------------------------------
476 function table.copy(t, seen)
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
488 function table.insert_all(t, other)
496 function table.key_value_swap(t)
498 for k,v in pairs(t) do
505 function table.shuffle(t, from, to, random)
508 random = random or math.random
509 local n = to - from + 1
512 local l = from + random(0, n-1)
513 t[l], t[r] = t[r], t[l]
519 --------------------------------------------------------------------------------
520 -- mainmenu only functions
521 --------------------------------------------------------------------------------
522 if INIT == "mainmenu" then
523 function core.get_game(index)
524 local games = core.get_games()
526 if index > 0 and index <= #games then
534 if core.gettext then -- for client and mainmenu
535 function fgettext_ne(text, ...)
536 text = core.gettext(text)
537 local arg = {n=select('#', ...), ...}
539 -- Insert positional parameters ($1, $2, ...)
542 while pos <= text:len() do
543 local newpos = text:find('[$]', pos)
544 if newpos == nil then
545 result = result .. text:sub(pos)
549 tonumber(text:sub(newpos+1, newpos+1))
550 result = result .. text:sub(pos, newpos-1)
551 .. tostring(arg[paramindex])
560 function fgettext(text, ...)
561 return core.formspec_escape(fgettext_ne(text, ...))
565 local ESCAPE_CHAR = string.char(0x1b)
567 function core.get_color_escape_sequence(color)
568 return ESCAPE_CHAR .. "(c@" .. color .. ")"
571 function core.get_background_escape_sequence(color)
572 return ESCAPE_CHAR .. "(b@" .. color .. ")"
575 function core.colorize(color, message)
576 local lines = tostring(message):split("\n", true)
577 local color_code = core.get_color_escape_sequence(color)
579 for i, line in ipairs(lines) do
580 lines[i] = color_code .. line
583 return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
587 function core.strip_foreground_colors(str)
588 return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
591 function core.strip_background_colors(str)
592 return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
595 function core.strip_colors(str)
596 return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
599 function core.translate(textdomain, str, ...)
601 if textdomain == "" then
602 start_seq = ESCAPE_CHAR .. "T"
604 start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
606 local arg = {n=select('#', ...), ...}
607 local end_seq = ESCAPE_CHAR .. "E"
609 local translated = str:gsub("@(.)", function(matched)
610 local c = string.byte(matched)
611 if string.byte("1") <= c and c <= string.byte("9") then
612 local a = c - string.byte("0")
613 if a ~= arg_index then
614 error("Escape sequences in string given to core.translate " ..
615 "are not in the correct order: got @" .. matched ..
616 "but expected @" .. tostring(arg_index))
619 error("Not enough arguments provided to core.translate")
621 arg_index = arg_index + 1
622 return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
623 elseif matched == "n" then
629 if arg_index < arg.n + 1 then
630 error("Too many arguments provided to core.translate")
632 return start_seq .. translated .. end_seq
635 function core.get_translator(textdomain)
636 return function(str, ...) return core.translate(textdomain or "", str, ...) end
639 --------------------------------------------------------------------------------
640 -- Returns the exact coordinate of a pointed surface
641 --------------------------------------------------------------------------------
642 function core.pointed_thing_to_face_pos(placer, pointed_thing)
643 -- Avoid crash in some situations when player is inside a node, causing
644 -- 'above' to equal 'under'.
645 if vector.equals(pointed_thing.above, pointed_thing.under) then
646 return pointed_thing.under
649 local eye_height = placer:get_properties().eye_height
650 local eye_offset_first = placer:get_eye_offset()
651 local node_pos = pointed_thing.under
652 local camera_pos = placer:get_pos()
653 local pos_off = vector.multiply(
654 vector.subtract(pointed_thing.above, node_pos), 0.5)
655 local look_dir = placer:get_look_dir()
659 for c, v in pairs(pos_off) do
668 local fine_pos = {[nc] = node_pos[nc] + offset}
669 camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
670 local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
673 fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
678 function core.string_to_privs(str, delim)
679 assert(type(str) == "string")
682 for _, priv in pairs(string.split(str, delim)) do
683 privs[priv:trim()] = true
688 function core.privs_to_string(privs, delim)
689 assert(type(privs) == "table")
692 for priv, bool in pairs(privs) do
694 list[#list + 1] = priv
697 return table.concat(list, delim)
700 function core.is_nan(number)
701 return number ~= number
704 --[[ Helper function for parsing an optionally relative number
705 of a chat command parameter, using the chat command tilde notation.
708 * arg: String snippet containing the number; possible values:
709 * "<number>": return as number
710 * "~<number>": return relative_to + <number>
711 * "~": return relative_to
712 * Anything else will return `nil`
713 * relative_to: Number to which the `arg` number might be relative to
716 A number or `nil`, depending on `arg.
719 * `core.parse_relative_number("5", 10)` returns 5
720 * `core.parse_relative_number("~5", 10)` returns 15
721 * `core.parse_relative_number("~", 10)` returns 10
723 function core.parse_relative_number(arg, relative_to)
726 elseif arg == "~" then
728 elseif string.sub(arg, 1, 1) == "~" then
729 local number = tonumber(string.sub(arg, 2))
733 if core.is_nan(number) or number == math.huge or number == -math.huge then
736 return relative_to + number
738 local number = tonumber(arg)
739 if core.is_nan(number) or number == math.huge or number == -math.huge then
746 --[[ Helper function to parse coordinates that might be relative
747 to another position; supports chat command tilde notation.
748 Intended to be used in chat command parameter parsing.
751 * x, y, z: Parsed x, y, and z coordinates as strings
752 * relative_to: Position to which to compare the position
754 Syntax of x, y and z:
755 * "<number>": return as number
756 * "~<number>": return <number> + player position on this axis
757 * "~": return player position on this axis
759 Returns: a vector or nil for invalid input or if player does not exist
761 function core.parse_coordinates(x, y, z, relative_to)
762 if not relative_to then
763 x, y, z = tonumber(x), tonumber(y), tonumber(z)
764 return x and y and z and { x = x, y = y, z = z }
766 local rx = core.parse_relative_number(x, relative_to.x)
767 local ry = core.parse_relative_number(y, relative_to.y)
768 local rz = core.parse_relative_number(z, relative_to.z)
769 return rx and ry and rz and { x = rx, y = ry, z = rz }