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 --------------------------------------------------------------------------------
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))
24 return string.format("<%s>", tp)
38 ["goto"] = true, -- Lua 5.2
52 local function is_valid_identifier(str)
53 if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
59 --------------------------------------------------------------------------------
60 -- Dumps values in a line-per-value format.
61 -- For example, {test = {"Testing..."}} becomes:
63 -- _["test"][1] = "Testing..."
64 -- This handles tables as keys and circular references properly.
65 -- It also handles multiple references well, writing the table only once.
66 -- The dumped argument is internal-only.
68 function dump2(o, name, dumped)
70 -- "dumped" is used to keep track of serialized tables to handle
71 -- multiple references and circular tables properly.
72 -- It only contains tables as keys. The value is the name that
73 -- the table has in the dump, eg:
74 -- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
76 if type(o) ~= "table" then
77 return string.format("%s = %s\n", name, basic_dump(o))
80 return string.format("%s = %s\n", name, dumped[o])
83 -- This contains a list of strings to be concatenated later (because
84 -- Lua is slow at individual concatenation).
86 for k, v in pairs(o) do
88 if type(k) == "table" then
92 -- Key tables don't have a name, so use one of
93 -- the form _G["table: 0xFFFFFFF"]
94 keyStr = string.format("_G[%q]", tostring(k))
96 t[#t + 1] = dump2(k, keyStr, dumped)
99 keyStr = basic_dump(k)
101 local vname = string.format("%s[%s]", name, keyStr)
102 t[#t + 1] = dump2(v, vname, dumped)
104 return string.format("%s = {}\n%s", name, table.concat(t))
107 --------------------------------------------------------------------------------
108 -- This dumps values in a one-statement format.
109 -- For example, {test = {"Testing..."}} becomes:
115 -- This supports tables as keys, but not circular references.
116 -- It performs poorly with multiple references as it writes out the full
118 -- The indent field specifies a indentation string, it defaults to a tab.
119 -- Use the empty string to disable indentation.
120 -- The dumped and level arguments are internal-only.
122 function dump(o, indent, nested, level)
124 if not level and t == "userdata" then
125 -- when userdata (e.g. player) is passed directly, print its metatable:
126 return "userdata metatable: " .. dump(getmetatable(o))
132 -- Contains table -> true/nil of currently nested tables
133 nested = nested or {}
135 return "<circular reference>"
138 indent = indent or "\t"
142 local dumped_indexes = {}
143 for i, v in ipairs(o) do
144 ret[#ret + 1] = dump(v, indent, nested, level + 1)
145 dumped_indexes[i] = true
147 for k, v in pairs(o) do
148 if not dumped_indexes[k] then
149 if type(k) ~= "string" or not is_valid_identifier(k) then
150 k = "["..dump(k, indent, nested, level + 1).."]"
152 v = dump(v, indent, nested, level + 1)
153 ret[#ret + 1] = k.." = "..v
158 local indent_str = "\n"..string.rep(indent, level)
159 local end_indent_str = "\n"..string.rep(indent, level - 1)
160 return string.format("{%s%s%s}",
162 table.concat(ret, ","..indent_str),
165 return "{"..table.concat(ret, ", ").."}"
168 --------------------------------------------------------------------------------
169 function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
171 max_splits = max_splits or -2
173 local pos, len = 1, #str
174 local plain = not sep_is_pattern
175 max_splits = max_splits + 1
177 local np, npe = string_find(str, delim, pos, plain)
178 np, npe = (np or (len+1)), (npe or (len+1))
179 if (not np) or (max_splits == 1) then
183 local s = string_sub(str, pos, np - 1)
184 if include_empty or (s ~= "") then
185 max_splits = max_splits - 1
186 items[#items + 1] = s
189 until (max_splits == 0) or (pos > (len + 1))
193 --------------------------------------------------------------------------------
194 function table.indexof(list, val)
195 for i, v in ipairs(list) do
203 --------------------------------------------------------------------------------
204 if INIT ~= "client" then
205 function file_exists(filename)
206 local f = io.open(filename, "r")
215 --------------------------------------------------------------------------------
216 function string:trim()
217 return (self:gsub("^%s*(.-)%s*$", "%1"))
220 --------------------------------------------------------------------------------
221 function math.hypot(x, y)
227 if x == 0 then return 0 end
229 return x * math.sqrt(1 + t * t)
232 --------------------------------------------------------------------------------
233 function math.sign(x, tolerance)
234 tolerance = tolerance or 0
235 if x > tolerance then
237 elseif x < -tolerance then
243 --------------------------------------------------------------------------------
244 function math.factorial(x)
245 assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
247 -- 171! is greater than the biggest double, no need to calculate
257 --------------------------------------------------------------------------------
258 function get_last_folder(text,count)
259 local parts = text:split(DIR_DELIM)
267 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
273 --------------------------------------------------------------------------------
274 function cleanup_path(temppath)
276 local parts = temppath:split("-")
279 if temppath ~= "" then
280 temppath = temppath .. "_"
282 temppath = temppath .. parts[i]
285 parts = temppath:split(".")
288 if temppath ~= "" then
289 temppath = temppath .. "_"
291 temppath = temppath .. parts[i]
294 parts = temppath:split("'")
297 if temppath ~= "" then
298 temppath = temppath .. ""
300 temppath = temppath .. parts[i]
303 parts = temppath:split(" ")
306 if temppath ~= "" then
309 temppath = temppath .. parts[i]
315 function core.formspec_escape(text)
317 text = string.gsub(text,"\\","\\\\")
318 text = string.gsub(text,"%]","\\]")
319 text = string.gsub(text,"%[","\\[")
320 text = string.gsub(text,";","\\;")
321 text = string.gsub(text,",","\\,")
327 function core.wrap_text(text, max_length, as_table)
330 if #text <= max_length then
331 return as_table and {text} or text
334 for word in text:gmatch('%S+') do
335 local cur_length = #table.concat(line, ' ')
336 if cur_length > 0 and cur_length + #word + 1 >= max_length then
337 -- word wouldn't fit on current line, move to next line
338 table.insert(result, table.concat(line, ' '))
341 table.insert(line, word)
344 table.insert(result, table.concat(line, ' '))
345 return as_table and result or table.concat(result, '\n')
348 --------------------------------------------------------------------------------
350 if INIT == "game" then
351 local dirs1 = {9, 18, 7, 12}
352 local dirs2 = {20, 23, 22, 21}
354 function core.rotate_and_place(itemstack, placer, pointed_thing,
355 infinitestacks, orient_flags, prevent_after_place)
356 orient_flags = orient_flags or {}
358 local unode = core.get_node_or_nil(pointed_thing.under)
362 local undef = core.registered_nodes[unode.name]
363 if undef and undef.on_rightclick then
364 return undef.on_rightclick(pointed_thing.under, unode, placer,
365 itemstack, pointed_thing)
367 local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
369 local above = pointed_thing.above
370 local under = pointed_thing.under
371 local iswall = (above.y == under.y)
372 local isceiling = not iswall and (above.y < under.y)
374 if undef and undef.buildable_to then
378 if orient_flags.force_floor then
381 elseif orient_flags.force_ceiling then
384 elseif orient_flags.force_wall then
387 elseif orient_flags.invert_wall then
393 param2 = dirs1[fdir + 1]
394 elseif isceiling then
395 if orient_flags.force_facedir then
398 param2 = dirs2[fdir + 1]
400 else -- place right side up
401 if orient_flags.force_facedir then
406 local old_itemstack = ItemStack(itemstack)
407 local new_itemstack = core.item_place_node(itemstack, placer,
408 pointed_thing, param2, prevent_after_place)
409 return infinitestacks and old_itemstack or new_itemstack
413 --------------------------------------------------------------------------------
414 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
415 --implies infinite stacks when performing a 6d rotation.
416 --------------------------------------------------------------------------------
417 local creative_mode_cache = core.settings:get_bool("creative_mode")
418 local function is_creative(name)
419 return creative_mode_cache or
420 core.check_player_privs(name, {creative = true})
423 core.rotate_node = function(itemstack, placer, pointed_thing)
424 local name = placer and placer:get_player_name() or ""
425 local invert_wall = placer and placer:get_player_control().sneak or false
426 return core.rotate_and_place(itemstack, placer, pointed_thing,
428 {invert_wall = invert_wall}, true)
432 --------------------------------------------------------------------------------
433 function core.explode_table_event(evt)
435 local parts = evt:split(":")
437 local t = parts[1]:trim()
438 local r = tonumber(parts[2]:trim())
439 local c = tonumber(parts[3]:trim())
440 if type(r) == "number" and type(c) == "number"
442 return {type=t, row=r, column=c}
446 return {type="INV", row=0, column=0}
449 --------------------------------------------------------------------------------
450 function core.explode_textlist_event(evt)
452 local parts = evt:split(":")
454 local t = parts[1]:trim()
455 local r = tonumber(parts[2]:trim())
456 if type(r) == "number" and t ~= "INV" then
457 return {type=t, index=r}
461 return {type="INV", index=0}
464 --------------------------------------------------------------------------------
465 function core.explode_scrollbar_event(evt)
466 local retval = core.explode_textlist_event(evt)
468 retval.value = retval.index
474 --------------------------------------------------------------------------------
475 function core.rgba(r, g, b, a)
476 return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
477 string.format("#%02X%02X%02X", r, g, b)
480 --------------------------------------------------------------------------------
481 function core.pos_to_string(pos, decimal_places)
485 if decimal_places ~= nil then
486 x = string.format("%." .. decimal_places .. "f", x)
487 y = string.format("%." .. decimal_places .. "f", y)
488 z = string.format("%." .. decimal_places .. "f", z)
490 return "(" .. x .. "," .. y .. "," .. z .. ")"
493 --------------------------------------------------------------------------------
494 function core.string_to_pos(value)
500 p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
501 if p.x and p.y and p.z then
508 p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
509 if p.x and p.y and p.z then
519 --------------------------------------------------------------------------------
520 function core.string_to_area(value)
521 local p1, p2 = unpack(value:split(") ("))
522 if p1 == nil or p2 == nil then
526 p1 = core.string_to_pos(p1 .. ")")
527 p2 = core.string_to_pos("(" .. p2)
528 if p1 == nil or p2 == nil then
535 local function test_string_to_area()
536 local p1, p2 = core.string_to_area("(10.0, 5, -2) ( 30.2, 4, -12.53)")
537 assert(p1.x == 10.0 and p1.y == 5 and p1.z == -2)
538 assert(p2.x == 30.2 and p2.y == 4 and p2.z == -12.53)
540 p1, p2 = core.string_to_area("(10.0, 5, -2 30.2, 4, -12.53")
541 assert(p1 == nil and p2 == nil)
543 p1, p2 = core.string_to_area("(10.0, 5,) -2 fgdf2, 4, -12.53")
544 assert(p1 == nil and p2 == nil)
547 test_string_to_area()
549 --------------------------------------------------------------------------------
550 function table.copy(t, seen)
554 for k, v in pairs(t) do
555 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
556 (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
562 function table.insert_all(t, other)
570 function table.key_value_swap(t)
572 for k,v in pairs(t) do
579 function table.shuffle(t, from, to, random)
582 random = random or math.random
583 local n = to - from + 1
586 local l = from + random(0, n-1)
587 t[l], t[r] = t[r], t[l]
593 --------------------------------------------------------------------------------
594 -- mainmenu only functions
595 --------------------------------------------------------------------------------
596 if INIT == "mainmenu" then
597 function core.get_game(index)
598 local games = core.get_games()
600 if index > 0 and index <= #games then
608 if INIT == "client" or INIT == "mainmenu" then
609 function fgettext_ne(text, ...)
610 text = core.gettext(text)
611 local arg = {n=select('#', ...), ...}
613 -- Insert positional parameters ($1, $2, ...)
616 while pos <= text:len() do
617 local newpos = text:find('[$]', pos)
618 if newpos == nil then
619 result = result .. text:sub(pos)
623 tonumber(text:sub(newpos+1, newpos+1))
624 result = result .. text:sub(pos, newpos-1)
625 .. tostring(arg[paramindex])
634 function fgettext(text, ...)
635 return core.formspec_escape(fgettext_ne(text, ...))
639 local ESCAPE_CHAR = string.char(0x1b)
641 function core.get_color_escape_sequence(color)
642 return ESCAPE_CHAR .. "(c@" .. color .. ")"
645 function core.get_background_escape_sequence(color)
646 return ESCAPE_CHAR .. "(b@" .. color .. ")"
649 function core.colorize(color, message)
650 local lines = tostring(message):split("\n", true)
651 local color_code = core.get_color_escape_sequence(color)
653 for i, line in ipairs(lines) do
654 lines[i] = color_code .. line
657 return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
661 function core.strip_foreground_colors(str)
662 return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
665 function core.strip_background_colors(str)
666 return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
669 function core.strip_colors(str)
670 return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
673 function core.translate(textdomain, str, ...)
675 if textdomain == "" then
676 start_seq = ESCAPE_CHAR .. "T"
678 start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
680 local arg = {n=select('#', ...), ...}
681 local end_seq = ESCAPE_CHAR .. "E"
683 local translated = str:gsub("@(.)", function(matched)
684 local c = string.byte(matched)
685 if string.byte("1") <= c and c <= string.byte("9") then
686 local a = c - string.byte("0")
687 if a ~= arg_index then
688 error("Escape sequences in string given to core.translate " ..
689 "are not in the correct order: got @" .. matched ..
690 "but expected @" .. tostring(arg_index))
693 error("Not enough arguments provided to core.translate")
695 arg_index = arg_index + 1
696 return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
697 elseif matched == "n" then
703 if arg_index < arg.n + 1 then
704 error("Too many arguments provided to core.translate")
706 return start_seq .. translated .. end_seq
709 function core.get_translator(textdomain)
710 return function(str, ...) return core.translate(textdomain or "", str, ...) end
713 --------------------------------------------------------------------------------
714 -- Returns the exact coordinate of a pointed surface
715 --------------------------------------------------------------------------------
716 function core.pointed_thing_to_face_pos(placer, pointed_thing)
717 -- Avoid crash in some situations when player is inside a node, causing
718 -- 'above' to equal 'under'.
719 if vector.equals(pointed_thing.above, pointed_thing.under) then
720 return pointed_thing.under
723 local eye_height = placer:get_properties().eye_height
724 local eye_offset_first = placer:get_eye_offset()
725 local node_pos = pointed_thing.under
726 local camera_pos = placer:get_pos()
727 local pos_off = vector.multiply(
728 vector.subtract(pointed_thing.above, node_pos), 0.5)
729 local look_dir = placer:get_look_dir()
733 for c, v in pairs(pos_off) do
742 local fine_pos = {[nc] = node_pos[nc] + offset}
743 camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
744 local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
747 fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
752 function core.string_to_privs(str, delim)
753 assert(type(str) == "string")
756 for _, priv in pairs(string.split(str, delim)) do
757 privs[priv:trim()] = true
762 function core.privs_to_string(privs, delim)
763 assert(type(privs) == "table")
766 for priv, bool in pairs(privs) do
768 list[#list + 1] = priv
771 return table.concat(list, delim)