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))
131 -- Contains table -> true/nil of currently nested tables
132 nested = nested or {}
134 return "<circular reference>"
137 indent = indent or "\t"
140 local dumped_indexes = {}
141 for i, v in ipairs(o) do
142 t[#t + 1] = dump(v, indent, nested, level + 1)
143 dumped_indexes[i] = true
145 for k, v in pairs(o) do
146 if not dumped_indexes[k] then
147 if type(k) ~= "string" or not is_valid_identifier(k) then
148 k = "["..dump(k, indent, nested, level + 1).."]"
150 v = dump(v, indent, nested, level + 1)
151 t[#t + 1] = k.." = "..v
156 local indent_str = "\n"..string.rep(indent, level)
157 local end_indent_str = "\n"..string.rep(indent, level - 1)
158 return string.format("{%s%s%s}",
160 table.concat(t, ","..indent_str),
163 return "{"..table.concat(t, ", ").."}"
166 --------------------------------------------------------------------------------
167 function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
169 max_splits = max_splits or -2
171 local pos, len = 1, #str
172 local plain = not sep_is_pattern
173 max_splits = max_splits + 1
175 local np, npe = string_find(str, delim, pos, plain)
176 np, npe = (np or (len+1)), (npe or (len+1))
177 if (not np) or (max_splits == 1) then
181 local s = string_sub(str, pos, np - 1)
182 if include_empty or (s ~= "") then
183 max_splits = max_splits - 1
184 items[#items + 1] = s
187 until (max_splits == 0) or (pos > (len + 1))
191 --------------------------------------------------------------------------------
192 function table.indexof(list, val)
193 for i, v in ipairs(list) do
201 assert(table.indexof({"foo", "bar"}, "foo") == 1)
202 assert(table.indexof({"foo", "bar"}, "baz") == -1)
204 --------------------------------------------------------------------------------
205 if INIT ~= "client" then
206 function file_exists(filename)
207 local f = io.open(filename, "r")
216 --------------------------------------------------------------------------------
217 function string:trim()
218 return (self:gsub("^%s*(.-)%s*$", "%1"))
221 assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")
223 --------------------------------------------------------------------------------
224 function math.hypot(x, y)
230 if x == 0 then return 0 end
232 return x * math.sqrt(1 + t * t)
235 --------------------------------------------------------------------------------
236 function math.sign(x, tolerance)
237 tolerance = tolerance or 0
238 if x > tolerance then
240 elseif x < -tolerance then
246 --------------------------------------------------------------------------------
247 function get_last_folder(text,count)
248 local parts = text:split(DIR_DELIM)
256 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
262 --------------------------------------------------------------------------------
263 function cleanup_path(temppath)
265 local parts = temppath:split("-")
268 if temppath ~= "" then
269 temppath = temppath .. "_"
271 temppath = temppath .. parts[i]
274 parts = temppath:split(".")
277 if temppath ~= "" then
278 temppath = temppath .. "_"
280 temppath = temppath .. parts[i]
283 parts = temppath:split("'")
286 if temppath ~= "" then
287 temppath = temppath .. ""
289 temppath = temppath .. parts[i]
292 parts = temppath:split(" ")
295 if temppath ~= "" then
298 temppath = temppath .. parts[i]
304 function core.formspec_escape(text)
306 text = string.gsub(text,"\\","\\\\")
307 text = string.gsub(text,"%]","\\]")
308 text = string.gsub(text,"%[","\\[")
309 text = string.gsub(text,";","\\;")
310 text = string.gsub(text,",","\\,")
316 function core.wrap_text(text, max_length, as_table)
319 if #text <= max_length then
320 return as_table and {text} or text
323 for word in text:gmatch('%S+') do
324 local cur_length = #table.concat(line, ' ')
325 if cur_length > 0 and cur_length + #word + 1 >= max_length then
326 -- word wouldn't fit on current line, move to next line
327 table.insert(result, table.concat(line, ' '))
330 table.insert(line, word)
333 table.insert(result, table.concat(line, ' '))
334 return as_table and result or table.concat(result, '\n')
337 --------------------------------------------------------------------------------
339 if INIT == "game" then
340 local dirs1 = {9, 18, 7, 12}
341 local dirs2 = {20, 23, 22, 21}
343 function core.rotate_and_place(itemstack, placer, pointed_thing,
344 infinitestacks, orient_flags, prevent_after_place)
345 orient_flags = orient_flags or {}
347 local unode = core.get_node_or_nil(pointed_thing.under)
351 local undef = core.registered_nodes[unode.name]
352 if undef and undef.on_rightclick then
353 return undef.on_rightclick(pointed_thing.under, unode, placer,
354 itemstack, pointed_thing)
356 local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
358 local above = pointed_thing.above
359 local under = pointed_thing.under
360 local iswall = (above.y == under.y)
361 local isceiling = not iswall and (above.y < under.y)
363 if undef and undef.buildable_to then
367 if orient_flags.force_floor then
370 elseif orient_flags.force_ceiling then
373 elseif orient_flags.force_wall then
376 elseif orient_flags.invert_wall then
382 param2 = dirs1[fdir + 1]
383 elseif isceiling then
384 if orient_flags.force_facedir then
387 param2 = dirs2[fdir + 1]
389 else -- place right side up
390 if orient_flags.force_facedir then
395 local old_itemstack = ItemStack(itemstack)
396 local new_itemstack, removed = core.item_place_node(
397 itemstack, placer, pointed_thing, param2, prevent_after_place
399 return infinitestacks and old_itemstack or new_itemstack
403 --------------------------------------------------------------------------------
404 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
405 --implies infinite stacks when performing a 6d rotation.
406 --------------------------------------------------------------------------------
407 local creative_mode_cache = core.settings:get_bool("creative_mode")
408 local function is_creative(name)
409 return creative_mode_cache or
410 core.check_player_privs(name, {creative = true})
413 core.rotate_node = function(itemstack, placer, pointed_thing)
414 local name = placer and placer:get_player_name() or ""
415 local invert_wall = placer and placer:get_player_control().sneak or false
416 core.rotate_and_place(itemstack, placer, pointed_thing,
418 {invert_wall = invert_wall}, true)
423 --------------------------------------------------------------------------------
424 function core.explode_table_event(evt)
426 local parts = evt:split(":")
428 local t = parts[1]:trim()
429 local r = tonumber(parts[2]:trim())
430 local c = tonumber(parts[3]:trim())
431 if type(r) == "number" and type(c) == "number"
433 return {type=t, row=r, column=c}
437 return {type="INV", row=0, column=0}
440 --------------------------------------------------------------------------------
441 function core.explode_textlist_event(evt)
443 local parts = evt:split(":")
445 local t = parts[1]:trim()
446 local r = tonumber(parts[2]:trim())
447 if type(r) == "number" and t ~= "INV" then
448 return {type=t, index=r}
452 return {type="INV", index=0}
455 --------------------------------------------------------------------------------
456 function core.explode_scrollbar_event(evt)
457 local retval = core.explode_textlist_event(evt)
459 retval.value = retval.index
465 --------------------------------------------------------------------------------
466 function core.rgba(r, g, b, a)
467 return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
468 string.format("#%02X%02X%02X", r, g, b)
471 --------------------------------------------------------------------------------
472 function core.pos_to_string(pos, decimal_places)
476 if decimal_places ~= nil then
477 x = string.format("%." .. decimal_places .. "f", x)
478 y = string.format("%." .. decimal_places .. "f", y)
479 z = string.format("%." .. decimal_places .. "f", z)
481 return "(" .. x .. "," .. y .. "," .. z .. ")"
484 --------------------------------------------------------------------------------
485 function core.string_to_pos(value)
491 p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
492 if p.x and p.y and p.z then
499 p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
500 if p.x and p.y and p.z then
509 assert(core.string_to_pos("10.0, 5, -2").x == 10)
510 assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
511 assert(core.string_to_pos("asd, 5, -2)") == nil)
513 --------------------------------------------------------------------------------
514 function core.string_to_area(value)
515 local p1, p2 = unpack(value:split(") ("))
516 if p1 == nil or p2 == nil then
520 p1 = core.string_to_pos(p1 .. ")")
521 p2 = core.string_to_pos("(" .. p2)
522 if p1 == nil or p2 == nil then
529 local function test_string_to_area()
530 local p1, p2 = core.string_to_area("(10.0, 5, -2) ( 30.2, 4, -12.53)")
531 assert(p1.x == 10.0 and p1.y == 5 and p1.z == -2)
532 assert(p2.x == 30.2 and p2.y == 4 and p2.z == -12.53)
534 p1, p2 = core.string_to_area("(10.0, 5, -2 30.2, 4, -12.53")
535 assert(p1 == nil and p2 == nil)
537 p1, p2 = core.string_to_area("(10.0, 5,) -2 fgdf2, 4, -12.53")
538 assert(p1 == nil and p2 == nil)
541 test_string_to_area()
543 --------------------------------------------------------------------------------
544 function table.copy(t, seen)
548 for k, v in pairs(t) do
549 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
550 (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
556 function table.insert_all(t, other)
564 --------------------------------------------------------------------------------
565 -- mainmenu only functions
566 --------------------------------------------------------------------------------
567 if INIT == "mainmenu" then
568 function core.get_game(index)
569 local games = core.get_games()
571 if index > 0 and index <= #games then
579 if INIT == "client" or INIT == "mainmenu" then
580 function fgettext_ne(text, ...)
581 text = core.gettext(text)
582 local arg = {n=select('#', ...), ...}
584 -- Insert positional parameters ($1, $2, ...)
587 while pos <= text:len() do
588 local newpos = text:find('[$]', pos)
589 if newpos == nil then
590 result = result .. text:sub(pos)
594 tonumber(text:sub(newpos+1, newpos+1))
595 result = result .. text:sub(pos, newpos-1)
596 .. tostring(arg[paramindex])
605 function fgettext(text, ...)
606 return core.formspec_escape(fgettext_ne(text, ...))
610 local ESCAPE_CHAR = string.char(0x1b)
612 function core.get_color_escape_sequence(color)
613 return ESCAPE_CHAR .. "(c@" .. color .. ")"
616 function core.get_background_escape_sequence(color)
617 return ESCAPE_CHAR .. "(b@" .. color .. ")"
620 function core.colorize(color, message)
621 local lines = tostring(message):split("\n", true)
622 local color_code = core.get_color_escape_sequence(color)
624 for i, line in ipairs(lines) do
625 lines[i] = color_code .. line
628 return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
632 function core.strip_foreground_colors(str)
633 return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
636 function core.strip_background_colors(str)
637 return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
640 function core.strip_colors(str)
641 return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
644 function core.translate(textdomain, str, ...)
646 if textdomain == "" then
647 start_seq = ESCAPE_CHAR .. "T"
649 start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
651 local arg = {n=select('#', ...), ...}
652 local end_seq = ESCAPE_CHAR .. "E"
654 local translated = str:gsub("@(.)", function(matched)
655 local c = string.byte(matched)
656 if string.byte("1") <= c and c <= string.byte("9") then
657 local a = c - string.byte("0")
658 if a ~= arg_index then
659 error("Escape sequences in string given to core.translate " ..
660 "are not in the correct order: got @" .. matched ..
661 "but expected @" .. tostring(arg_index))
664 error("Not enough arguments provided to core.translate")
666 arg_index = arg_index + 1
667 return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
668 elseif matched == "n" then
674 if arg_index < arg.n + 1 then
675 error("Too many arguments provided to core.translate")
677 return start_seq .. translated .. end_seq
680 function core.get_translator(textdomain)
681 return function(str, ...) return core.translate(textdomain or "", str, ...) end
684 --------------------------------------------------------------------------------
685 -- Returns the exact coordinate of a pointed surface
686 --------------------------------------------------------------------------------
687 function core.pointed_thing_to_face_pos(placer, pointed_thing)
688 -- Avoid crash in some situations when player is inside a node, causing
689 -- 'above' to equal 'under'.
690 if vector.equals(pointed_thing.above, pointed_thing.under) then
691 return pointed_thing.under
694 local eye_height = placer:get_properties().eye_height
695 local eye_offset_first = placer:get_eye_offset()
696 local node_pos = pointed_thing.under
697 local camera_pos = placer:get_pos()
698 local pos_off = vector.multiply(
699 vector.subtract(pointed_thing.above, node_pos), 0.5)
700 local look_dir = placer:get_look_dir()
704 for c, v in pairs(pos_off) do
713 local fine_pos = {[nc] = node_pos[nc] + offset}
714 camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
715 local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
718 fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
723 function core.string_to_privs(str, delim)
724 assert(type(str) == "string")
727 for _, priv in pairs(string.split(str, delim)) do
728 privs[priv:trim()] = true
733 function core.privs_to_string(privs, delim)
734 assert(type(privs) == "table")
737 for priv, bool in pairs(privs) do
739 list[#list + 1] = priv
742 return table.concat(list, delim)
745 assert(core.string_to_privs("a,b").b == true)
746 assert(core.privs_to_string({a=true,b=true}) == "a,b")