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)
123 if type(o) ~= "table" then
126 -- Contains table -> true/nil of currently nested tables
127 nested = nested or {}
129 return "<circular reference>"
132 indent = indent or "\t"
135 local dumped_indexes = {}
136 for i, v in ipairs(o) do
137 t[#t + 1] = dump(v, indent, nested, level + 1)
138 dumped_indexes[i] = true
140 for k, v in pairs(o) do
141 if not dumped_indexes[k] then
142 if type(k) ~= "string" or not is_valid_identifier(k) then
143 k = "["..dump(k, indent, nested, level + 1).."]"
145 v = dump(v, indent, nested, level + 1)
146 t[#t + 1] = k.." = "..v
151 local indent_str = "\n"..string.rep(indent, level)
152 local end_indent_str = "\n"..string.rep(indent, level - 1)
153 return string.format("{%s%s%s}",
155 table.concat(t, ","..indent_str),
158 return "{"..table.concat(t, ", ").."}"
161 --------------------------------------------------------------------------------
162 function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
164 max_splits = max_splits or -1
166 local pos, len, seplen = 1, #str, #delim
167 local plain = not sep_is_pattern
168 max_splits = max_splits + 1
170 local np, npe = string_find(str, delim, pos, plain)
171 np, npe = (np or (len+1)), (npe or (len+1))
172 if (not np) or (max_splits == 1) then
176 local s = string_sub(str, pos, np - 1)
177 if include_empty or (s ~= "") then
178 max_splits = max_splits - 1
179 items[#items + 1] = s
182 until (max_splits == 0) or (pos > (len + 1))
186 --------------------------------------------------------------------------------
187 function table.indexof(list, val)
188 for i, v in ipairs(list) do
196 assert(table.indexof({"foo", "bar"}, "foo") == 1)
197 assert(table.indexof({"foo", "bar"}, "baz") == -1)
199 --------------------------------------------------------------------------------
200 if INIT ~= "client" then
201 function file_exists(filename)
202 local f = io.open(filename, "r")
211 --------------------------------------------------------------------------------
212 function string:trim()
213 return (self:gsub("^%s*(.-)%s*$", "%1"))
216 assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")
218 --------------------------------------------------------------------------------
219 function math.hypot(x, y)
225 if x == 0 then return 0 end
227 return x * math.sqrt(1 + t * t)
230 --------------------------------------------------------------------------------
231 function math.sign(x, tolerance)
232 tolerance = tolerance or 0
233 if x > tolerance then
235 elseif x < -tolerance then
241 --------------------------------------------------------------------------------
242 function get_last_folder(text,count)
243 local parts = text:split(DIR_DELIM)
251 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
257 --------------------------------------------------------------------------------
258 function cleanup_path(temppath)
260 local parts = temppath:split("-")
263 if temppath ~= "" then
264 temppath = temppath .. "_"
266 temppath = temppath .. parts[i]
269 parts = temppath:split(".")
272 if temppath ~= "" then
273 temppath = temppath .. "_"
275 temppath = temppath .. parts[i]
278 parts = temppath:split("'")
281 if temppath ~= "" then
282 temppath = temppath .. ""
284 temppath = temppath .. parts[i]
287 parts = temppath:split(" ")
290 if temppath ~= "" then
293 temppath = temppath .. parts[i]
299 function core.formspec_escape(text)
301 text = string.gsub(text,"\\","\\\\")
302 text = string.gsub(text,"%]","\\]")
303 text = string.gsub(text,"%[","\\[")
304 text = string.gsub(text,";","\\;")
305 text = string.gsub(text,",","\\,")
311 function core.wrap_text(text, max_length, as_table)
314 if #text <= max_length then
315 return as_table and {text} or text
318 for word in text:gmatch('%S+') do
319 local cur_length = #table.concat(line, ' ')
320 if cur_length > 0 and cur_length + #word + 1 >= max_length then
321 -- word wouldn't fit on current line, move to next line
322 table.insert(result, table.concat(line, ' '))
325 table.insert(line, word)
328 table.insert(result, table.concat(line, ' '))
329 return as_table and result or table.concat(result, '\n')
332 --------------------------------------------------------------------------------
334 if INIT == "game" then
335 local dirs1 = {9, 18, 7, 12}
336 local dirs2 = {20, 23, 22, 21}
338 function core.rotate_and_place(itemstack, placer, pointed_thing,
339 infinitestacks, orient_flags)
340 orient_flags = orient_flags or {}
342 local unode = core.get_node_or_nil(pointed_thing.under)
346 local undef = core.registered_nodes[unode.name]
347 if undef and undef.on_rightclick then
348 return undef.on_rightclick(pointed_thing.under, unode, placer,
349 itemstack, pointed_thing)
351 local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
353 local above = pointed_thing.above
354 local under = pointed_thing.under
355 local iswall = (above.y == under.y)
356 local isceiling = not iswall and (above.y < under.y)
358 if undef and undef.buildable_to then
362 if orient_flags.force_floor then
365 elseif orient_flags.force_ceiling then
368 elseif orient_flags.force_wall then
371 elseif orient_flags.invert_wall then
377 param2 = dirs1[fdir + 1]
378 elseif isceiling then
379 if orient_flags.force_facedir then
382 param2 = dirs2[fdir + 1]
384 else -- place right side up
385 if orient_flags.force_facedir then
390 local old_itemstack = ItemStack(itemstack)
391 local new_itemstack, removed = core.item_place_node(
392 itemstack, placer, pointed_thing, param2
394 return infinitestacks and old_itemstack or new_itemstack
398 --------------------------------------------------------------------------------
399 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
400 --implies infinite stacks when performing a 6d rotation.
401 --------------------------------------------------------------------------------
402 local creative_mode_cache = core.settings:get_bool("creative_mode")
403 local function is_creative(name)
404 return creative_mode_cache or
405 core.check_player_privs(name, {creative = true})
408 core.rotate_node = function(itemstack, placer, pointed_thing)
409 local name = placer and placer:get_player_name() or ""
410 local invert_wall = placer and placer:get_player_control().sneak or false
411 core.rotate_and_place(itemstack, placer, pointed_thing,
413 {invert_wall = invert_wall})
418 --------------------------------------------------------------------------------
419 function core.explode_table_event(evt)
421 local parts = evt:split(":")
423 local t = parts[1]:trim()
424 local r = tonumber(parts[2]:trim())
425 local c = tonumber(parts[3]:trim())
426 if type(r) == "number" and type(c) == "number"
428 return {type=t, row=r, column=c}
432 return {type="INV", row=0, column=0}
435 --------------------------------------------------------------------------------
436 function core.explode_textlist_event(evt)
438 local parts = evt:split(":")
440 local t = parts[1]:trim()
441 local r = tonumber(parts[2]:trim())
442 if type(r) == "number" and t ~= "INV" then
443 return {type=t, index=r}
447 return {type="INV", index=0}
450 --------------------------------------------------------------------------------
451 function core.explode_scrollbar_event(evt)
452 local retval = core.explode_textlist_event(evt)
454 retval.value = retval.index
460 --------------------------------------------------------------------------------
461 function core.rgba(r, g, b, a)
462 return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
463 string.format("#%02X%02X%02X", r, g, b)
466 --------------------------------------------------------------------------------
467 function core.pos_to_string(pos, decimal_places)
471 if decimal_places ~= nil then
472 x = string.format("%." .. decimal_places .. "f", x)
473 y = string.format("%." .. decimal_places .. "f", y)
474 z = string.format("%." .. decimal_places .. "f", z)
476 return "(" .. x .. "," .. y .. "," .. z .. ")"
479 --------------------------------------------------------------------------------
480 function core.string_to_pos(value)
486 p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
487 if p.x and p.y and p.z then
494 p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
495 if p.x and p.y and p.z then
504 assert(core.string_to_pos("10.0, 5, -2").x == 10)
505 assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
506 assert(core.string_to_pos("asd, 5, -2)") == nil)
508 --------------------------------------------------------------------------------
509 function core.string_to_area(value)
510 local p1, p2 = unpack(value:split(") ("))
511 if p1 == nil or p2 == nil then
515 p1 = core.string_to_pos(p1 .. ")")
516 p2 = core.string_to_pos("(" .. p2)
517 if p1 == nil or p2 == nil then
524 local function test_string_to_area()
525 local p1, p2 = core.string_to_area("(10.0, 5, -2) ( 30.2, 4, -12.53)")
526 assert(p1.x == 10.0 and p1.y == 5 and p1.z == -2)
527 assert(p2.x == 30.2 and p2.y == 4 and p2.z == -12.53)
529 p1, p2 = core.string_to_area("(10.0, 5, -2 30.2, 4, -12.53")
530 assert(p1 == nil and p2 == nil)
532 p1, p2 = core.string_to_area("(10.0, 5,) -2 fgdf2, 4, -12.53")
533 assert(p1 == nil and p2 == nil)
536 test_string_to_area()
538 --------------------------------------------------------------------------------
539 function table.copy(t, seen)
543 for k, v in pairs(t) do
544 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
545 (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
549 --------------------------------------------------------------------------------
550 -- mainmenu only functions
551 --------------------------------------------------------------------------------
552 if INIT == "mainmenu" then
553 function core.get_game(index)
554 local games = game.get_games()
556 if index > 0 and index <= #games then
564 if INIT == "client" or INIT == "mainmenu" then
565 function fgettext_ne(text, ...)
566 text = core.gettext(text)
567 local arg = {n=select('#', ...), ...}
569 -- Insert positional parameters ($1, $2, ...)
572 while pos <= text:len() do
573 local newpos = text:find('[$]', pos)
574 if newpos == nil then
575 result = result .. text:sub(pos)
579 tonumber(text:sub(newpos+1, newpos+1))
580 result = result .. text:sub(pos, newpos-1)
581 .. tostring(arg[paramindex])
590 function fgettext(text, ...)
591 return core.formspec_escape(fgettext_ne(text, ...))
595 local ESCAPE_CHAR = string.char(0x1b)
597 function core.get_color_escape_sequence(color)
598 return ESCAPE_CHAR .. "(c@" .. color .. ")"
601 function core.get_background_escape_sequence(color)
602 return ESCAPE_CHAR .. "(b@" .. color .. ")"
605 function core.colorize(color, message)
606 local lines = tostring(message):split("\n", true)
607 local color_code = core.get_color_escape_sequence(color)
609 for i, line in ipairs(lines) do
610 lines[i] = color_code .. line
613 return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
617 function core.strip_foreground_colors(str)
618 return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
621 function core.strip_background_colors(str)
622 return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
625 function core.strip_colors(str)
626 return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
629 function core.translate(textdomain, str, ...)
631 if textdomain == "" then
632 start_seq = ESCAPE_CHAR .. "T"
634 start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
636 local arg = {n=select('#', ...), ...}
637 local end_seq = ESCAPE_CHAR .. "E"
639 local translated = str:gsub("@(.)", function(matched)
640 local c = string.byte(matched)
641 if string.byte("1") <= c and c <= string.byte("9") then
642 local a = c - string.byte("0")
643 if a ~= arg_index then
644 error("Escape sequences in string given to core.translate " ..
645 "are not in the correct order: got @" .. matched ..
646 "but expected @" .. tostring(arg_index))
649 error("Not enough arguments provided to core.translate")
651 arg_index = arg_index + 1
652 return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
653 elseif matched == "n" then
659 if arg_index < arg.n + 1 then
660 error("Too many arguments provided to core.translate")
662 return start_seq .. translated .. end_seq
665 function core.get_translator(textdomain)
666 return function(str, ...) return core.translate(textdomain or "", str, ...) end
669 --------------------------------------------------------------------------------
670 -- Returns the exact coordinate of a pointed surface
671 --------------------------------------------------------------------------------
672 function core.pointed_thing_to_face_pos(placer, pointed_thing)
673 local eye_offset_first = placer:get_eye_offset()
674 local node_pos = pointed_thing.under
675 local camera_pos = placer:get_pos()
676 local pos_off = vector.multiply(
677 vector.subtract(pointed_thing.above, node_pos), 0.5)
678 local look_dir = placer:get_look_dir()
682 for c, v in pairs(pos_off) do
691 local fine_pos = {[nc] = node_pos[nc] + offset}
692 camera_pos.y = camera_pos.y + 1.625 + eye_offset_first.y / 10
693 local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
696 fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
701 function core.string_to_privs(str, delim)
702 assert(type(str) == "string")
705 for _, priv in pairs(string.split(str, delim)) do
706 privs[priv:trim()] = true
711 function core.privs_to_string(privs, delim)
712 assert(type(privs) == "table")
715 for priv, bool in pairs(privs) do
717 list[#list + 1] = priv
720 return table.concat(list, delim)
723 assert(core.string_to_privs("a,b").b == true)
724 assert(core.privs_to_string({a=true,b=true}) == "a,b")