1 -- Minetest: builtin/misc_helpers.lua
3 --------------------------------------------------------------------------------
4 -- Localize functions to avoid table lookups (better performance).
5 local table_insert = table.insert
6 local string_sub, string_find = string.sub, string.find
8 --------------------------------------------------------------------------------
11 if tp == "number" then
13 elseif tp == "string" then
14 return string.format("%q", o)
15 elseif tp == "boolean" then
17 elseif tp == "nil" then
19 -- Uncomment for full function dumping support.
20 -- Not currently enabled because bytecode isn't very human-readable and
21 -- dump's output is intended for humans.
22 --elseif tp == "function" then
23 -- return string.format("loadstring(%q)", string.dump(o))
25 return string.format("<%s>", tp)
39 ["goto"] = true, -- Lua 5.2
53 local function is_valid_identifier(str)
54 if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
60 --------------------------------------------------------------------------------
61 -- Dumps values in a line-per-value format.
62 -- For example, {test = {"Testing..."}} becomes:
64 -- _["test"][1] = "Testing..."
65 -- This handles tables as keys and circular references properly.
66 -- It also handles multiple references well, writing the table only once.
67 -- The dumped argument is internal-only.
69 function dump2(o, name, dumped)
71 -- "dumped" is used to keep track of serialized tables to handle
72 -- multiple references and circular tables properly.
73 -- It only contains tables as keys. The value is the name that
74 -- the table has in the dump, eg:
75 -- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
77 if type(o) ~= "table" then
78 return string.format("%s = %s\n", name, basic_dump(o))
81 return string.format("%s = %s\n", name, dumped[o])
84 -- This contains a list of strings to be concatenated later (because
85 -- Lua is slow at individual concatenation).
87 for k, v in pairs(o) do
89 if type(k) == "table" then
93 -- Key tables don't have a name, so use one of
94 -- the form _G["table: 0xFFFFFFF"]
95 keyStr = string.format("_G[%q]", tostring(k))
97 table_insert(t, dump2(k, keyStr, dumped))
100 keyStr = basic_dump(k)
102 local vname = string.format("%s[%s]", name, keyStr)
103 table_insert(t, dump2(v, vname, dumped))
105 return string.format("%s = {}\n%s", name, table.concat(t))
108 --------------------------------------------------------------------------------
109 -- This dumps values in a one-statement format.
110 -- For example, {test = {"Testing..."}} becomes:
116 -- This supports tables as keys, but not circular references.
117 -- It performs poorly with multiple references as it writes out the full
119 -- The indent field specifies a indentation string, it defaults to a tab.
120 -- Use the empty string to disable indentation.
121 -- The dumped and level arguments are internal-only.
123 function dump(o, indent, nested, level)
124 if type(o) ~= "table" then
127 -- Contains table -> true/nil of currently nested tables
128 nested = nested or {}
130 return "<circular reference>"
133 indent = indent or "\t"
136 local dumped_indexes = {}
137 for i, v in ipairs(o) do
138 table_insert(t, dump(v, indent, nested, level + 1))
139 dumped_indexes[i] = true
141 for k, v in pairs(o) do
142 if not dumped_indexes[k] then
143 if type(k) ~= "string" or not is_valid_identifier(k) then
144 k = "["..dump(k, indent, nested, level + 1).."]"
146 v = dump(v, indent, nested, level + 1)
147 table_insert(t, k.." = "..v)
152 local indent_str = "\n"..string.rep(indent, level)
153 local end_indent_str = "\n"..string.rep(indent, level - 1)
154 return string.format("{%s%s%s}",
156 table.concat(t, ","..indent_str),
159 return "{"..table.concat(t, ", ").."}"
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 table_insert(items, s)
182 until (max_splits == 0) or (pos > (len + 1))
186 --------------------------------------------------------------------------------
187 function file_exists(filename)
188 local f = io.open(filename, "r")
197 --------------------------------------------------------------------------------
198 function string:trim()
199 return (self:gsub("^%s*(.-)%s*$", "%1"))
202 assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")
204 --------------------------------------------------------------------------------
205 function math.hypot(x, y)
211 if x == 0 then return 0 end
213 return x * math.sqrt(1 + t * t)
216 --------------------------------------------------------------------------------
217 function math.sign(x, tolerance)
218 tolerance = tolerance or 0
219 if x > tolerance then
221 elseif x < -tolerance then
227 --------------------------------------------------------------------------------
228 function get_last_folder(text,count)
229 local parts = text:split(DIR_DELIM)
237 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
243 --------------------------------------------------------------------------------
244 function cleanup_path(temppath)
246 local parts = temppath:split("-")
249 if temppath ~= "" then
250 temppath = temppath .. "_"
252 temppath = temppath .. parts[i]
255 parts = temppath:split(".")
258 if temppath ~= "" then
259 temppath = temppath .. "_"
261 temppath = temppath .. parts[i]
264 parts = temppath:split("'")
267 if temppath ~= "" then
268 temppath = temppath .. ""
270 temppath = temppath .. parts[i]
273 parts = temppath:split(" ")
276 if temppath ~= "" then
279 temppath = temppath .. parts[i]
285 function core.formspec_escape(text)
287 text = string.gsub(text,"\\","\\\\")
288 text = string.gsub(text,"%]","\\]")
289 text = string.gsub(text,"%[","\\[")
290 text = string.gsub(text,";","\\;")
291 text = string.gsub(text,",","\\,")
297 function core.splittext(text,charlimit)
300 local current_idx = 1
302 local start,stop = string_find(text, " ", current_idx)
303 local nl_start,nl_stop = string_find(text, "\n", current_idx)
304 local gotnewline = false
305 if nl_start ~= nil and (start == nil or nl_start < start) then
311 while start ~= nil do
312 if string.len(last_line) + (stop-start) > charlimit then
313 table_insert(retval, last_line)
317 if last_line ~= "" then
318 last_line = last_line .. " "
321 last_line = last_line .. string_sub(text, current_idx, stop - 1)
324 table_insert(retval, last_line)
330 start,stop = string_find(text, " ", current_idx)
331 nl_start,nl_stop = string_find(text, "\n", current_idx)
333 if nl_start ~= nil and (start == nil or nl_start < start) then
340 --add last part of text
341 if string.len(last_line) + (string.len(text) - current_idx) > charlimit then
342 table_insert(retval, last_line)
343 table_insert(retval, string_sub(text, current_idx))
345 last_line = last_line .. " " .. string_sub(text, current_idx)
346 table_insert(retval, last_line)
352 --------------------------------------------------------------------------------
354 if INIT == "game" then
355 local dirs1 = {9, 18, 7, 12}
356 local dirs2 = {20, 23, 22, 21}
358 function core.rotate_and_place(itemstack, placer, pointed_thing,
359 infinitestacks, orient_flags)
360 orient_flags = orient_flags or {}
362 local unode = core.get_node_or_nil(pointed_thing.under)
366 local undef = core.registered_nodes[unode.name]
367 if undef and undef.on_rightclick then
368 undef.on_rightclick(pointed_thing.under, unode, placer,
369 itemstack, pointed_thing)
372 local pitch = placer:get_look_pitch()
373 local fdir = core.dir_to_facedir(placer:get_look_dir())
374 local wield_name = itemstack:get_name()
376 local above = pointed_thing.above
377 local under = pointed_thing.under
378 local iswall = (above.y == under.y)
379 local isceiling = not iswall and (above.y < under.y)
380 local anode = core.get_node_or_nil(above)
384 local pos = pointed_thing.above
387 if undef and undef.buildable_to then
388 pos = pointed_thing.under
393 if core.is_protected(pos, placer:get_player_name()) then
394 core.record_protection_violation(pos,
395 placer:get_player_name())
399 local ndef = core.registered_nodes[node.name]
400 if not ndef or not ndef.buildable_to then
404 if orient_flags.force_floor then
407 elseif orient_flags.force_ceiling then
410 elseif orient_flags.force_wall then
413 elseif orient_flags.invert_wall then
418 core.set_node(pos, {name = wield_name,
419 param2 = dirs1[fdir+1]})
420 elseif isceiling then
421 if orient_flags.force_facedir then
422 core.set_node(pos, {name = wield_name,
425 core.set_node(pos, {name = wield_name,
426 param2 = dirs2[fdir+1]})
428 else -- place right side up
429 if orient_flags.force_facedir then
430 core.set_node(pos, {name = wield_name,
433 core.set_node(pos, {name = wield_name,
438 if not infinitestacks then
439 itemstack:take_item()
445 --------------------------------------------------------------------------------
446 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
447 --implies infinite stacks when performing a 6d rotation.
448 --------------------------------------------------------------------------------
451 core.rotate_node = function(itemstack, placer, pointed_thing)
452 core.rotate_and_place(itemstack, placer, pointed_thing,
453 core.setting_getbool("creative_mode"),
454 {invert_wall = placer:get_player_control().sneak})
459 --------------------------------------------------------------------------------
460 function core.explode_table_event(evt)
462 local parts = evt:split(":")
464 local t = parts[1]:trim()
465 local r = tonumber(parts[2]:trim())
466 local c = tonumber(parts[3]:trim())
467 if type(r) == "number" and type(c) == "number"
469 return {type=t, row=r, column=c}
473 return {type="INV", row=0, column=0}
476 --------------------------------------------------------------------------------
477 function core.explode_textlist_event(evt)
479 local parts = evt:split(":")
481 local t = parts[1]:trim()
482 local r = tonumber(parts[2]:trim())
483 if type(r) == "number" and t ~= "INV" then
484 return {type=t, index=r}
488 return {type="INV", index=0}
491 --------------------------------------------------------------------------------
492 function core.explode_scrollbar_event(evt)
493 local retval = core.explode_textlist_event(evt)
495 retval.value = retval.index
501 --------------------------------------------------------------------------------
502 function core.pos_to_string(pos, decimal_places)
506 if decimal_places ~= nil then
507 x = string.format("%." .. decimal_places .. "f", x)
508 y = string.format("%." .. decimal_places .. "f", y)
509 z = string.format("%." .. decimal_places .. "f", z)
511 return "(" .. x .. "," .. y .. "," .. z .. ")"
514 --------------------------------------------------------------------------------
515 function core.string_to_pos(value)
521 p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
522 if p.x and p.y and p.z then
529 p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
530 if p.x and p.y and p.z then
539 assert(core.string_to_pos("10.0, 5, -2").x == 10)
540 assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
541 assert(core.string_to_pos("asd, 5, -2)") == nil)
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
554 --------------------------------------------------------------------------------
555 -- mainmenu only functions
556 --------------------------------------------------------------------------------
557 if INIT == "mainmenu" then
558 function core.get_game(index)
559 local games = game.get_games()
561 if index > 0 and index <= #games then
568 function fgettext_ne(text, ...)
569 text = core.gettext(text)
570 local arg = {n=select('#', ...), ...}
572 -- Insert positional parameters ($1, $2, ...)
575 while pos <= text:len() do
576 local newpos = text:find('[$]', pos)
577 if newpos == nil then
578 result = result .. text:sub(pos)
582 tonumber(text:sub(newpos+1, newpos+1))
583 result = result .. text:sub(pos, newpos-1)
584 .. tostring(arg[paramindex])
593 function fgettext(text, ...)
594 return core.formspec_escape(fgettext_ne(text, ...))