1 -- Minetest: builtin/misc_helpers.lua
3 --------------------------------------------------------------------------------
8 elseif tp == "string" then
9 return string.format("%q", o)
10 elseif tp == "boolean" then
12 elseif tp == "nil" then
14 -- Uncomment for full function dumping support.
15 -- Not currently enabled because bytecode isn't very human-readable and
16 -- dump's output is intended for humans.
17 --elseif tp == "function" then
18 -- return string.format("loadstring(%q)", string.dump(o))
20 return string.format("<%s>", tp)
34 ["goto"] = true, -- Lua 5.2
48 local function is_valid_identifier(str)
49 if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
55 --------------------------------------------------------------------------------
56 -- Dumps values in a line-per-value format.
57 -- For example, {test = {"Testing..."}} becomes:
59 -- _["test"][1] = "Testing..."
60 -- This handles tables as keys and circular references properly.
61 -- It also handles multiple references well, writing the table only once.
62 -- The dumped argument is internal-only.
64 function dump2(o, name, dumped)
66 -- "dumped" is used to keep track of serialized tables to handle
67 -- multiple references and circular tables properly.
68 -- It only contains tables as keys. The value is the name that
69 -- the table has in the dump, eg:
70 -- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
72 if type(o) ~= "table" then
73 return string.format("%s = %s\n", name, basic_dump(o))
76 return string.format("%s = %s\n", name, dumped[o])
79 -- This contains a list of strings to be concatenated later (because
80 -- Lua is slow at individual concatenation).
82 for k, v in pairs(o) do
84 if type(k) == "table" then
88 -- Key tables don't have a name, so use one of
89 -- the form _G["table: 0xFFFFFFF"]
90 keyStr = string.format("_G[%q]", tostring(k))
92 table.insert(t, dump2(k, keyStr, dumped))
95 keyStr = basic_dump(k)
97 local vname = string.format("%s[%s]", name, keyStr)
98 table.insert(t, dump2(v, vname, dumped))
100 return string.format("%s = {}\n%s", name, table.concat(t))
103 --------------------------------------------------------------------------------
104 -- This dumps values in a one-statement format.
105 -- For example, {test = {"Testing..."}} becomes:
111 -- This supports tables as keys, but not circular references.
112 -- It performs poorly with multiple references as it writes out the full
114 -- The indent field specifies a indentation string, it defaults to a tab.
115 -- Use the empty string to disable indentation.
116 -- The dumped and level arguments are internal-only.
118 function dump(o, indent, nested, level)
119 if type(o) ~= "table" then
122 -- Contains table -> true/nil of currently nested tables
123 nested = nested or {}
125 return "<circular reference>"
128 indent = indent or "\t"
131 local dumped_indexes = {}
132 for i, v in ipairs(o) do
133 table.insert(t, dump(v, indent, nested, level + 1))
134 dumped_indexes[i] = true
136 for k, v in pairs(o) do
137 if not dumped_indexes[k] then
138 if type(k) ~= "string" or not is_valid_identifier(k) then
139 k = "["..dump(k, indent, nested, level + 1).."]"
141 v = dump(v, indent, nested, level + 1)
142 table.insert(t, k.." = "..v)
147 local indent_str = "\n"..string.rep(indent, level)
148 local end_indent_str = "\n"..string.rep(indent, level - 1)
149 return string.format("{%s%s%s}",
151 table.concat(t, ","..indent_str),
154 return "{"..table.concat(t, ", ").."}"
157 --------------------------------------------------------------------------------
158 -- Localize functions to avoid table lookups (better performance).
159 local table_insert = table.insert
160 local str_sub, str_find = string.sub, string.find
161 function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
163 max_splits = max_splits or -1
165 local pos, len, seplen = 1, #str, #delim
166 local plain = not sep_is_pattern
167 max_splits = max_splits + 1
169 local np, npe = str_find(str, delim, pos, plain)
170 np, npe = (np or (len+1)), (npe or (len+1))
171 if (not np) or (max_splits == 1) then
175 local s = str_sub(str, pos, np - 1)
176 if include_empty or (s ~= "") then
177 max_splits = max_splits - 1
178 table_insert(items, s)
181 until (max_splits == 0) or (pos > (len + 1))
185 --------------------------------------------------------------------------------
186 function file_exists(filename)
187 local f = io.open(filename, "r")
196 --------------------------------------------------------------------------------
197 function string:trim()
198 return (self:gsub("^%s*(.-)%s*$", "%1"))
201 assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")
203 --------------------------------------------------------------------------------
204 function math.hypot(x, y)
210 if x == 0 then return 0 end
212 return x * math.sqrt(1 + t * t)
215 --------------------------------------------------------------------------------
216 function math.sign(x, tolerance)
217 tolerance = tolerance or 0
218 if x > tolerance then
220 elseif x < -tolerance then
226 --------------------------------------------------------------------------------
227 function get_last_folder(text,count)
228 local parts = text:split(DIR_DELIM)
236 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
242 --------------------------------------------------------------------------------
243 function cleanup_path(temppath)
245 local parts = temppath:split("-")
248 if temppath ~= "" then
249 temppath = temppath .. "_"
251 temppath = temppath .. parts[i]
254 parts = temppath:split(".")
257 if temppath ~= "" then
258 temppath = temppath .. "_"
260 temppath = temppath .. parts[i]
263 parts = temppath:split("'")
266 if temppath ~= "" then
267 temppath = temppath .. ""
269 temppath = temppath .. parts[i]
272 parts = temppath:split(" ")
275 if temppath ~= "" then
278 temppath = temppath .. parts[i]
284 function core.formspec_escape(text)
286 text = string.gsub(text,"\\","\\\\")
287 text = string.gsub(text,"%]","\\]")
288 text = string.gsub(text,"%[","\\[")
289 text = string.gsub(text,";","\\;")
290 text = string.gsub(text,",","\\,")
296 function core.splittext(text,charlimit)
299 local current_idx = 1
301 local start,stop = string.find(text," ",current_idx)
302 local nl_start,nl_stop = string.find(text,"\n",current_idx)
303 local gotnewline = false
304 if nl_start ~= nil and (start == nil or nl_start < start) then
310 while start ~= nil do
311 if string.len(last_line) + (stop-start) > charlimit then
312 table.insert(retval,last_line)
316 if last_line ~= "" then
317 last_line = last_line .. " "
320 last_line = last_line .. string.sub(text,current_idx,stop -1)
323 table.insert(retval,last_line)
329 start,stop = string.find(text," ",current_idx)
330 nl_start,nl_stop = string.find(text,"\n",current_idx)
332 if nl_start ~= nil and (start == nil or nl_start < start) then
339 --add last part of text
340 if string.len(last_line) + (string.len(text) - current_idx) > charlimit then
341 table.insert(retval,last_line)
342 table.insert(retval,string.sub(text,current_idx))
344 last_line = last_line .. " " .. string.sub(text,current_idx)
345 table.insert(retval,last_line)
351 --------------------------------------------------------------------------------
353 if INIT == "game" then
354 local dirs1 = {9, 18, 7, 12}
355 local dirs2 = {20, 23, 22, 21}
357 function core.rotate_and_place(itemstack, placer, pointed_thing,
358 infinitestacks, orient_flags)
359 orient_flags = orient_flags or {}
361 local unode = core.get_node_or_nil(pointed_thing.under)
365 local undef = core.registered_nodes[unode.name]
366 if undef and undef.on_rightclick then
367 undef.on_rightclick(pointed_thing.under, unode, placer,
368 itemstack, pointed_thing)
371 local pitch = placer:get_look_pitch()
372 local fdir = core.dir_to_facedir(placer:get_look_dir())
373 local wield_name = itemstack:get_name()
375 local above = pointed_thing.above
376 local under = pointed_thing.under
377 local iswall = (above.y == under.y)
378 local isceiling = not iswall and (above.y < under.y)
379 local anode = core.get_node_or_nil(above)
383 local pos = pointed_thing.above
386 if undef and undef.buildable_to then
387 pos = pointed_thing.under
392 if core.is_protected(pos, placer:get_player_name()) then
393 core.record_protection_violation(pos,
394 placer:get_player_name())
398 local ndef = core.registered_nodes[node.name]
399 if not ndef or not ndef.buildable_to then
403 if orient_flags.force_floor then
406 elseif orient_flags.force_ceiling then
409 elseif orient_flags.force_wall then
412 elseif orient_flags.invert_wall then
417 core.set_node(pos, {name = wield_name,
418 param2 = dirs1[fdir+1]})
419 elseif isceiling then
420 if orient_flags.force_facedir then
421 core.set_node(pos, {name = wield_name,
424 core.set_node(pos, {name = wield_name,
425 param2 = dirs2[fdir+1]})
427 else -- place right side up
428 if orient_flags.force_facedir then
429 core.set_node(pos, {name = wield_name,
432 core.set_node(pos, {name = wield_name,
437 if not infinitestacks then
438 itemstack:take_item()
444 --------------------------------------------------------------------------------
445 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
446 --implies infinite stacks when performing a 6d rotation.
447 --------------------------------------------------------------------------------
450 core.rotate_node = function(itemstack, placer, pointed_thing)
451 core.rotate_and_place(itemstack, placer, pointed_thing,
452 core.setting_getbool("creative_mode"),
453 {invert_wall = placer:get_player_control().sneak})
458 --------------------------------------------------------------------------------
459 function core.explode_table_event(evt)
461 local parts = evt:split(":")
463 local t = parts[1]:trim()
464 local r = tonumber(parts[2]:trim())
465 local c = tonumber(parts[3]:trim())
466 if type(r) == "number" and type(c) == "number"
468 return {type=t, row=r, column=c}
472 return {type="INV", row=0, column=0}
475 --------------------------------------------------------------------------------
476 function core.explode_textlist_event(evt)
478 local parts = evt:split(":")
480 local t = parts[1]:trim()
481 local r = tonumber(parts[2]:trim())
482 if type(r) == "number" and t ~= "INV" then
483 return {type=t, index=r}
487 return {type="INV", index=0}
490 --------------------------------------------------------------------------------
491 function core.explode_scrollbar_event(evt)
492 local retval = core.explode_textlist_event(evt)
494 retval.value = retval.index
500 --------------------------------------------------------------------------------
501 function core.pos_to_string(pos, decimal_places)
505 if decimal_places ~= nil then
506 x = string.format("%." .. decimal_places .. "f", x)
507 y = string.format("%." .. decimal_places .. "f", y)
508 z = string.format("%." .. decimal_places .. "f", z)
510 return "(" .. x .. "," .. y .. "," .. z .. ")"
513 --------------------------------------------------------------------------------
514 function core.string_to_pos(value)
520 p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
521 if p.x and p.y and p.z then
528 p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
529 if p.x and p.y and p.z then
538 assert(core.string_to_pos("10.0, 5, -2").x == 10)
539 assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
540 assert(core.string_to_pos("asd, 5, -2)") == nil)
542 --------------------------------------------------------------------------------
543 function table.copy(t, seen)
547 for k, v in pairs(t) do
548 n[type(k) ~= "table" and k or seen[k] or table.copy(k, seen)] =
549 type(v) ~= "table" and v or seen[v] or table.copy(v, seen)
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(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])
590 return core.formspec_escape(text)