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:gsub("^%s*(.-)%s*$", "%1"))
210 --------------------------------------------------------------------------------
211 function math.hypot(x, y)
217 if x == 0 then return 0 end
219 return x * math.sqrt(1 + t * t)
222 --------------------------------------------------------------------------------
223 function math.sign(x, tolerance)
224 tolerance = tolerance or 0
225 if x > tolerance then
227 elseif x < -tolerance then
233 --------------------------------------------------------------------------------
234 function math.factorial(x)
235 assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
237 -- 171! is greater than the biggest double, no need to calculate
247 function core.formspec_escape(text)
249 text = string.gsub(text,"\\","\\\\")
250 text = string.gsub(text,"%]","\\]")
251 text = string.gsub(text,"%[","\\[")
252 text = string.gsub(text,";","\\;")
253 text = string.gsub(text,",","\\,")
259 function core.wrap_text(text, max_length, as_table)
262 if #text <= max_length then
263 return as_table and {text} or text
266 for word in text:gmatch('%S+') do
267 local cur_length = #table.concat(line, ' ')
268 if cur_length > 0 and cur_length + #word + 1 >= max_length then
269 -- word wouldn't fit on current line, move to next line
270 table.insert(result, table.concat(line, ' '))
273 table.insert(line, word)
276 table.insert(result, table.concat(line, ' '))
277 return as_table and result or table.concat(result, '\n')
280 --------------------------------------------------------------------------------
282 if INIT == "game" then
283 local dirs1 = {9, 18, 7, 12}
284 local dirs2 = {20, 23, 22, 21}
286 function core.rotate_and_place(itemstack, placer, pointed_thing,
287 infinitestacks, orient_flags, prevent_after_place)
288 orient_flags = orient_flags or {}
290 local unode = core.get_node_or_nil(pointed_thing.under)
294 local undef = core.registered_nodes[unode.name]
295 local sneaking = placer and placer:get_player_control().sneak
296 if undef and undef.on_rightclick and not sneaking then
297 return undef.on_rightclick(pointed_thing.under, unode, placer,
298 itemstack, pointed_thing)
300 local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
302 local above = pointed_thing.above
303 local under = pointed_thing.under
304 local iswall = (above.y == under.y)
305 local isceiling = not iswall and (above.y < under.y)
307 if undef and undef.buildable_to then
311 if orient_flags.force_floor then
314 elseif orient_flags.force_ceiling then
317 elseif orient_flags.force_wall then
320 elseif orient_flags.invert_wall then
326 param2 = dirs1[fdir + 1]
327 elseif isceiling then
328 if orient_flags.force_facedir then
331 param2 = dirs2[fdir + 1]
333 else -- place right side up
334 if orient_flags.force_facedir then
339 local old_itemstack = ItemStack(itemstack)
340 local new_itemstack = core.item_place_node(itemstack, placer,
341 pointed_thing, param2, prevent_after_place)
342 return infinitestacks and old_itemstack or new_itemstack
346 --------------------------------------------------------------------------------
347 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
348 --implies infinite stacks when performing a 6d rotation.
349 --------------------------------------------------------------------------------
350 core.rotate_node = function(itemstack, placer, pointed_thing)
351 local name = placer and placer:get_player_name() or ""
352 local invert_wall = placer and placer:get_player_control().sneak or false
353 return core.rotate_and_place(itemstack, placer, pointed_thing,
354 core.is_creative_enabled(name),
355 {invert_wall = invert_wall}, true)
359 --------------------------------------------------------------------------------
360 function core.explode_table_event(evt)
362 local parts = evt:split(":")
364 local t = parts[1]:trim()
365 local r = tonumber(parts[2]:trim())
366 local c = tonumber(parts[3]:trim())
367 if type(r) == "number" and type(c) == "number"
369 return {type=t, row=r, column=c}
373 return {type="INV", row=0, column=0}
376 --------------------------------------------------------------------------------
377 function core.explode_textlist_event(evt)
379 local parts = evt:split(":")
381 local t = parts[1]:trim()
382 local r = tonumber(parts[2]:trim())
383 if type(r) == "number" and t ~= "INV" then
384 return {type=t, index=r}
388 return {type="INV", index=0}
391 --------------------------------------------------------------------------------
392 function core.explode_scrollbar_event(evt)
393 local retval = core.explode_textlist_event(evt)
395 retval.value = retval.index
401 --------------------------------------------------------------------------------
402 function core.rgba(r, g, b, a)
403 return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
404 string.format("#%02X%02X%02X", r, g, b)
407 --------------------------------------------------------------------------------
408 function core.pos_to_string(pos, decimal_places)
412 if decimal_places ~= nil then
413 x = string.format("%." .. decimal_places .. "f", x)
414 y = string.format("%." .. decimal_places .. "f", y)
415 z = string.format("%." .. decimal_places .. "f", z)
417 return "(" .. x .. "," .. y .. "," .. z .. ")"
420 --------------------------------------------------------------------------------
421 function core.string_to_pos(value)
427 p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
428 if p.x and p.y and p.z then
435 p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
436 if p.x and p.y and p.z then
446 --------------------------------------------------------------------------------
447 function core.string_to_area(value)
448 local p1, p2 = unpack(value:split(") ("))
449 if p1 == nil or p2 == nil then
453 p1 = core.string_to_pos(p1 .. ")")
454 p2 = core.string_to_pos("(" .. p2)
455 if p1 == nil or p2 == nil then
462 local function test_string_to_area()
463 local p1, p2 = core.string_to_area("(10.0, 5, -2) ( 30.2, 4, -12.53)")
464 assert(p1.x == 10.0 and p1.y == 5 and p1.z == -2)
465 assert(p2.x == 30.2 and p2.y == 4 and p2.z == -12.53)
467 p1, p2 = core.string_to_area("(10.0, 5, -2 30.2, 4, -12.53")
468 assert(p1 == nil and p2 == nil)
470 p1, p2 = core.string_to_area("(10.0, 5,) -2 fgdf2, 4, -12.53")
471 assert(p1 == nil and p2 == nil)
474 test_string_to_area()
476 --------------------------------------------------------------------------------
477 function table.copy(t, seen)
481 for k, v in pairs(t) do
482 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
483 (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
489 function table.insert_all(t, other)
497 function table.key_value_swap(t)
499 for k,v in pairs(t) do
506 function table.shuffle(t, from, to, random)
509 random = random or math.random
510 local n = to - from + 1
513 local l = from + random(0, n-1)
514 t[l], t[r] = t[r], t[l]
520 --------------------------------------------------------------------------------
521 -- mainmenu only functions
522 --------------------------------------------------------------------------------
523 if INIT == "mainmenu" then
524 function core.get_game(index)
525 local games = core.get_games()
527 if index > 0 and index <= #games then
535 if INIT == "client" or INIT == "mainmenu" then
536 function fgettext_ne(text, ...)
537 text = core.gettext(text)
538 local arg = {n=select('#', ...), ...}
540 -- Insert positional parameters ($1, $2, ...)
543 while pos <= text:len() do
544 local newpos = text:find('[$]', pos)
545 if newpos == nil then
546 result = result .. text:sub(pos)
550 tonumber(text:sub(newpos+1, newpos+1))
551 result = result .. text:sub(pos, newpos-1)
552 .. tostring(arg[paramindex])
561 function fgettext(text, ...)
562 return core.formspec_escape(fgettext_ne(text, ...))
566 local ESCAPE_CHAR = string.char(0x1b)
568 function core.get_color_escape_sequence(color)
569 return ESCAPE_CHAR .. "(c@" .. color .. ")"
572 function core.get_background_escape_sequence(color)
573 return ESCAPE_CHAR .. "(b@" .. color .. ")"
576 function core.colorize(color, message)
577 local lines = tostring(message):split("\n", true)
578 local color_code = core.get_color_escape_sequence(color)
580 for i, line in ipairs(lines) do
581 lines[i] = color_code .. line
584 return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
588 function core.strip_foreground_colors(str)
589 return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
592 function core.strip_background_colors(str)
593 return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
596 function core.strip_colors(str)
597 return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
600 function core.translate(textdomain, str, ...)
602 if textdomain == "" then
603 start_seq = ESCAPE_CHAR .. "T"
605 start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
607 local arg = {n=select('#', ...), ...}
608 local end_seq = ESCAPE_CHAR .. "E"
610 local translated = str:gsub("@(.)", function(matched)
611 local c = string.byte(matched)
612 if string.byte("1") <= c and c <= string.byte("9") then
613 local a = c - string.byte("0")
614 if a ~= arg_index then
615 error("Escape sequences in string given to core.translate " ..
616 "are not in the correct order: got @" .. matched ..
617 "but expected @" .. tostring(arg_index))
620 error("Not enough arguments provided to core.translate")
622 arg_index = arg_index + 1
623 return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
624 elseif matched == "n" then
630 if arg_index < arg.n + 1 then
631 error("Too many arguments provided to core.translate")
633 return start_seq .. translated .. end_seq
636 function core.get_translator(textdomain)
637 return function(str, ...) return core.translate(textdomain or "", str, ...) end
640 --------------------------------------------------------------------------------
641 -- Returns the exact coordinate of a pointed surface
642 --------------------------------------------------------------------------------
643 function core.pointed_thing_to_face_pos(placer, pointed_thing)
644 -- Avoid crash in some situations when player is inside a node, causing
645 -- 'above' to equal 'under'.
646 if vector.equals(pointed_thing.above, pointed_thing.under) then
647 return pointed_thing.under
650 local eye_height = placer:get_properties().eye_height
651 local eye_offset_first = placer:get_eye_offset()
652 local node_pos = pointed_thing.under
653 local camera_pos = placer:get_pos()
654 local pos_off = vector.multiply(
655 vector.subtract(pointed_thing.above, node_pos), 0.5)
656 local look_dir = placer:get_look_dir()
660 for c, v in pairs(pos_off) do
669 local fine_pos = {[nc] = node_pos[nc] + offset}
670 camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
671 local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
674 fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
679 function core.string_to_privs(str, delim)
680 assert(type(str) == "string")
683 for _, priv in pairs(string.split(str, delim)) do
684 privs[priv:trim()] = true
689 function core.privs_to_string(privs, delim)
690 assert(type(privs) == "table")
693 for priv, bool in pairs(privs) do
695 list[#list + 1] = priv
698 return table.concat(list, delim)