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 get_last_folder(text,count)
217 local parts = text:split(DIR_DELIM)
225 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
231 --------------------------------------------------------------------------------
232 function cleanup_path(temppath)
234 local parts = temppath:split("-")
237 if temppath ~= "" then
238 temppath = temppath .. "_"
240 temppath = temppath .. parts[i]
243 parts = temppath:split(".")
246 if temppath ~= "" then
247 temppath = temppath .. "_"
249 temppath = temppath .. parts[i]
252 parts = temppath:split("'")
255 if temppath ~= "" then
256 temppath = temppath .. ""
258 temppath = temppath .. parts[i]
261 parts = temppath:split(" ")
264 if temppath ~= "" then
267 temppath = temppath .. parts[i]
273 function core.formspec_escape(text)
275 text = string.gsub(text,"\\","\\\\")
276 text = string.gsub(text,"%]","\\]")
277 text = string.gsub(text,"%[","\\[")
278 text = string.gsub(text,";","\\;")
279 text = string.gsub(text,",","\\,")
285 function core.splittext(text,charlimit)
288 local current_idx = 1
290 local start,stop = string.find(text," ",current_idx)
291 local nl_start,nl_stop = string.find(text,"\n",current_idx)
292 local gotnewline = false
293 if nl_start ~= nil and (start == nil or nl_start < start) then
299 while start ~= nil do
300 if string.len(last_line) + (stop-start) > charlimit then
301 table.insert(retval,last_line)
305 if last_line ~= "" then
306 last_line = last_line .. " "
309 last_line = last_line .. string.sub(text,current_idx,stop -1)
312 table.insert(retval,last_line)
318 start,stop = string.find(text," ",current_idx)
319 nl_start,nl_stop = string.find(text,"\n",current_idx)
321 if nl_start ~= nil and (start == nil or nl_start < start) then
328 --add last part of text
329 if string.len(last_line) + (string.len(text) - current_idx) > charlimit then
330 table.insert(retval,last_line)
331 table.insert(retval,string.sub(text,current_idx))
333 last_line = last_line .. " " .. string.sub(text,current_idx)
334 table.insert(retval,last_line)
340 --------------------------------------------------------------------------------
342 if INIT == "game" then
343 local dirs1 = {8, 17, 6, 15}
344 local dirs2 = {22, 21, 20, 23}
346 function core.rotate_and_place(itemstack, placer, pointed_thing,
347 infinitestacks, orient_flags)
348 orient_flags = orient_flags or {}
350 local unode = core.get_node_or_nil(pointed_thing.under)
354 local undef = core.registered_nodes[unode.name]
355 if undef and undef.on_rightclick then
356 undef.on_rightclick(pointed_thing.under, unode, placer,
357 itemstack, pointed_thing)
360 local pitch = placer:get_look_pitch()
361 local fdir = core.dir_to_facedir(placer:get_look_dir())
362 local wield_name = itemstack:get_name()
364 local above = pointed_thing.above
365 local under = pointed_thing.under
366 local iswall = (above.y == under.y)
367 local isceiling = not iswall and (above.y < under.y)
368 local anode = core.get_node_or_nil(above)
372 local pos = pointed_thing.above
375 if undef and undef.buildable_to then
376 pos = pointed_thing.under
381 if core.is_protected(pos, placer:get_player_name()) then
382 core.record_protection_violation(pos,
383 placer:get_player_name())
387 local ndef = core.registered_nodes[node.name]
388 if not ndef or not ndef.buildable_to then
392 if orient_flags.force_floor then
395 elseif orient_flags.force_ceiling then
398 elseif orient_flags.force_wall then
401 elseif orient_flags.invert_wall then
406 core.set_node(pos, {name = wield_name,
407 param2 = dirs1[fdir+1]})
408 elseif isceiling then
409 if orient_flags.force_facedir then
410 core.set_node(pos, {name = wield_name,
413 core.set_node(pos, {name = wield_name,
414 param2 = dirs2[fdir+1]})
416 else -- place right side up
417 if orient_flags.force_facedir then
418 core.set_node(pos, {name = wield_name,
421 core.set_node(pos, {name = wield_name,
426 if not infinitestacks then
427 itemstack:take_item()
433 --------------------------------------------------------------------------------
434 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
435 --implies infinite stacks when performing a 6d rotation.
436 --------------------------------------------------------------------------------
439 core.rotate_node = function(itemstack, placer, pointed_thing)
440 core.rotate_and_place(itemstack, placer, pointed_thing,
441 core.setting_getbool("creative_mode"),
442 {invert_wall = placer:get_player_control().sneak})
447 --------------------------------------------------------------------------------
448 function core.explode_table_event(evt)
450 local parts = evt:split(":")
452 local t = parts[1]:trim()
453 local r = tonumber(parts[2]:trim())
454 local c = tonumber(parts[3]:trim())
455 if type(r) == "number" and type(c) == "number" and t ~= "INV" then
456 return {type=t, row=r, column=c}
460 return {type="INV", row=0, column=0}
463 --------------------------------------------------------------------------------
464 function core.explode_textlist_event(evt)
466 local parts = evt:split(":")
468 local t = parts[1]:trim()
469 local r = tonumber(parts[2]:trim())
470 if type(r) == "number" and t ~= "INV" then
471 return {type=t, index=r}
475 return {type="INV", index=0}
478 --------------------------------------------------------------------------------
479 function core.explode_scrollbar_event(evt)
480 local retval = core.explode_textlist_event(evt)
482 retval.value = retval.index
488 --------------------------------------------------------------------------------
489 function core.pos_to_string(pos)
490 return "(" .. pos.x .. "," .. pos.y .. "," .. pos.z .. ")"
493 --------------------------------------------------------------------------------
494 function table.copy(t, seen)
498 for k, v in pairs(t) do
499 n[type(k) ~= "table" and k or seen[k] or table.copy(k, seen)] =
500 type(v) ~= "table" and v or seen[v] or table.copy(v, seen)
505 --------------------------------------------------------------------------------
506 -- mainmenu only functions
507 --------------------------------------------------------------------------------
508 if INIT == "mainmenu" then
509 function core.get_game(index)
510 local games = game.get_games()
512 if index > 0 and index <= #games then
519 function fgettext(text, ...)
520 text = core.gettext(text)
521 local arg = {n=select('#', ...), ...}
523 -- Insert positional parameters ($1, $2, ...)
526 while pos <= text:len() do
527 newpos = text:find('[$]', pos)
528 if newpos == nil then
529 result = result .. text:sub(pos)
532 paramindex = tonumber(text:sub(newpos+1, newpos+1))
533 result = result .. text:sub(pos, newpos-1) .. tostring(arg[paramindex])
539 return core.formspec_escape(text)