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 function string.split(str, delim, include_empty, max_splits)
160 max_splits = max_splits or 0
164 for part, pos in str:gmatch("(.-)[" .. delim .. "]()") do
166 if include_empty or part ~= "" then
167 num_splits = num_splits + 1
168 fields[num_splits] = part
169 if max_splits > 0 and num_splits + 1 >= max_splits then
174 -- Handle the last field
175 if max_splits <= 0 or num_splits <= max_splits then
176 local last_part = str:sub(last_pos)
177 if include_empty or last_part ~= "" then
178 fields[num_splits + 1] = last_part
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 = {8, 17, 6, 15}
355 local dirs2 = {22, 21, 20, 23}
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)
502 return "(" .. pos.x .. "," .. pos.y .. "," .. pos.z .. ")"
505 --------------------------------------------------------------------------------
506 function table.copy(t, seen)
510 for k, v in pairs(t) do
511 n[type(k) ~= "table" and k or seen[k] or table.copy(k, seen)] =
512 type(v) ~= "table" and v or seen[v] or table.copy(v, seen)
517 --------------------------------------------------------------------------------
518 -- mainmenu only functions
519 --------------------------------------------------------------------------------
520 if INIT == "mainmenu" then
521 function core.get_game(index)
522 local games = game.get_games()
524 if index > 0 and index <= #games then
531 function fgettext(text, ...)
532 text = core.gettext(text)
533 local arg = {n=select('#', ...), ...}
535 -- Insert positional parameters ($1, $2, ...)
538 while pos <= text:len() do
539 local newpos = text:find('[$]', pos)
540 if newpos == nil then
541 result = result .. text:sub(pos)
545 tonumber(text:sub(newpos+1, newpos+1))
546 result = result .. text:sub(pos, newpos-1)
547 .. tostring(arg[paramindex])
553 return core.formspec_escape(text)