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 --------------------------------------------------------------------------------
163 function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
165 max_splits = max_splits or -1
167 local pos, len, seplen = 1, #str, #delim
168 local plain = not sep_is_pattern
169 max_splits = max_splits + 1
171 local np, npe = string_find(str, delim, pos, plain)
172 np, npe = (np or (len+1)), (npe or (len+1))
173 if (not np) or (max_splits == 1) then
177 local s = string_sub(str, pos, np - 1)
178 if include_empty or (s ~= "") then
179 max_splits = max_splits - 1
180 table_insert(items, s)
183 until (max_splits == 0) or (pos > (len + 1))
187 --------------------------------------------------------------------------------
188 function table.indexof(list, val)
190 if list[i] == val then
197 assert(table.indexof({"foo", "bar"}, "foo") == 1)
198 assert(table.indexof({"foo", "bar"}, "baz") == -1)
200 --------------------------------------------------------------------------------
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.splittext(text,charlimit)
314 local current_idx = 1
316 local start,stop = string_find(text, " ", current_idx)
317 local nl_start,nl_stop = string_find(text, "\n", current_idx)
318 local gotnewline = false
319 if nl_start ~= nil and (start == nil or nl_start < start) then
325 while start ~= nil do
326 if string.len(last_line) + (stop-start) > charlimit then
327 table_insert(retval, last_line)
331 if last_line ~= "" then
332 last_line = last_line .. " "
335 last_line = last_line .. string_sub(text, current_idx, stop - 1)
338 table_insert(retval, last_line)
344 start,stop = string_find(text, " ", current_idx)
345 nl_start,nl_stop = string_find(text, "\n", current_idx)
347 if nl_start ~= nil and (start == nil or nl_start < start) then
354 --add last part of text
355 if string.len(last_line) + (string.len(text) - current_idx) > charlimit then
356 table_insert(retval, last_line)
357 table_insert(retval, string_sub(text, current_idx))
359 last_line = last_line .. " " .. string_sub(text, current_idx)
360 table_insert(retval, last_line)
366 --------------------------------------------------------------------------------
368 if INIT == "game" then
369 local dirs1 = {9, 18, 7, 12}
370 local dirs2 = {20, 23, 22, 21}
372 function core.rotate_and_place(itemstack, placer, pointed_thing,
373 infinitestacks, orient_flags)
374 orient_flags = orient_flags or {}
376 local unode = core.get_node_or_nil(pointed_thing.under)
380 local undef = core.registered_nodes[unode.name]
381 if undef and undef.on_rightclick then
382 undef.on_rightclick(pointed_thing.under, unode, placer,
383 itemstack, pointed_thing)
386 local pitch = placer:get_look_pitch()
387 local fdir = core.dir_to_facedir(placer:get_look_dir())
388 local wield_name = itemstack:get_name()
390 local above = pointed_thing.above
391 local under = pointed_thing.under
392 local iswall = (above.y == under.y)
393 local isceiling = not iswall and (above.y < under.y)
394 local anode = core.get_node_or_nil(above)
398 local pos = pointed_thing.above
401 if undef and undef.buildable_to then
402 pos = pointed_thing.under
407 if core.is_protected(pos, placer:get_player_name()) then
408 core.record_protection_violation(pos,
409 placer:get_player_name())
413 local ndef = core.registered_nodes[node.name]
414 if not ndef or not ndef.buildable_to then
418 if orient_flags.force_floor then
421 elseif orient_flags.force_ceiling then
424 elseif orient_flags.force_wall then
427 elseif orient_flags.invert_wall then
432 core.set_node(pos, {name = wield_name,
433 param2 = dirs1[fdir+1]})
434 elseif isceiling then
435 if orient_flags.force_facedir then
436 core.set_node(pos, {name = wield_name,
439 core.set_node(pos, {name = wield_name,
440 param2 = dirs2[fdir+1]})
442 else -- place right side up
443 if orient_flags.force_facedir then
444 core.set_node(pos, {name = wield_name,
447 core.set_node(pos, {name = wield_name,
452 if not infinitestacks then
453 itemstack:take_item()
459 --------------------------------------------------------------------------------
460 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
461 --implies infinite stacks when performing a 6d rotation.
462 --------------------------------------------------------------------------------
465 core.rotate_node = function(itemstack, placer, pointed_thing)
466 core.rotate_and_place(itemstack, placer, pointed_thing,
467 core.setting_getbool("creative_mode"),
468 {invert_wall = placer:get_player_control().sneak})
473 --------------------------------------------------------------------------------
474 function core.explode_table_event(evt)
476 local parts = evt:split(":")
478 local t = parts[1]:trim()
479 local r = tonumber(parts[2]:trim())
480 local c = tonumber(parts[3]:trim())
481 if type(r) == "number" and type(c) == "number"
483 return {type=t, row=r, column=c}
487 return {type="INV", row=0, column=0}
490 --------------------------------------------------------------------------------
491 function core.explode_textlist_event(evt)
493 local parts = evt:split(":")
495 local t = parts[1]:trim()
496 local r = tonumber(parts[2]:trim())
497 if type(r) == "number" and t ~= "INV" then
498 return {type=t, index=r}
502 return {type="INV", index=0}
505 --------------------------------------------------------------------------------
506 function core.explode_scrollbar_event(evt)
507 local retval = core.explode_textlist_event(evt)
509 retval.value = retval.index
515 --------------------------------------------------------------------------------
516 function core.pos_to_string(pos, decimal_places)
520 if decimal_places ~= nil then
521 x = string.format("%." .. decimal_places .. "f", x)
522 y = string.format("%." .. decimal_places .. "f", y)
523 z = string.format("%." .. decimal_places .. "f", z)
525 return "(" .. x .. "," .. y .. "," .. z .. ")"
528 --------------------------------------------------------------------------------
529 function core.string_to_pos(value)
535 p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
536 if p.x and p.y and p.z then
543 p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
544 if p.x and p.y and p.z then
553 assert(core.string_to_pos("10.0, 5, -2").x == 10)
554 assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
555 assert(core.string_to_pos("asd, 5, -2)") == nil)
557 --------------------------------------------------------------------------------
558 function table.copy(t, seen)
562 for k, v in pairs(t) do
563 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
564 (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
568 --------------------------------------------------------------------------------
569 -- mainmenu only functions
570 --------------------------------------------------------------------------------
571 if INIT == "mainmenu" then
572 function core.get_game(index)
573 local games = game.get_games()
575 if index > 0 and index <= #games then
582 function fgettext_ne(text, ...)
583 text = core.gettext(text)
584 local arg = {n=select('#', ...), ...}
586 -- Insert positional parameters ($1, $2, ...)
589 while pos <= text:len() do
590 local newpos = text:find('[$]', pos)
591 if newpos == nil then
592 result = result .. text:sub(pos)
596 tonumber(text:sub(newpos+1, newpos+1))
597 result = result .. text:sub(pos, newpos-1)
598 .. tostring(arg[paramindex])
607 function fgettext(text, ...)
608 return core.formspec_escape(fgettext_ne(text, ...))