]> git.lizzy.rs Git - minetest.git/blob - builtin/common/misc_helpers.lua
deeba788ea49ae551e62c6b7f550b0556f1479c7
[minetest.git] / builtin / common / misc_helpers.lua
1 -- Minetest: builtin/misc_helpers.lua
2
3 --------------------------------------------------------------------------------
4 function basic_dump(o)
5         local tp = type(o)
6         if tp == "number" then
7                 return tostring(o)
8         elseif tp == "string" then
9                 return string.format("%q", o)
10         elseif tp == "boolean" then
11                 return tostring(o)
12         elseif tp == "nil" then
13                 return "nil"
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))
19         else
20                 return string.format("<%s>", tp)
21         end
22 end
23
24 local keywords = {
25         ["and"] = true,
26         ["break"] = true,
27         ["do"] = true,
28         ["else"] = true,
29         ["elseif"] = true,
30         ["end"] = true,
31         ["false"] = true,
32         ["for"] = true,
33         ["function"] = true,
34         ["goto"] = true,  -- Lua 5.2
35         ["if"] = true,
36         ["in"] = true,
37         ["local"] = true,
38         ["nil"] = true,
39         ["not"] = true,
40         ["or"] = true,
41         ["repeat"] = true,
42         ["return"] = true,
43         ["then"] = true,
44         ["true"] = true,
45         ["until"] = true,
46         ["while"] = true,
47 }
48 local function is_valid_identifier(str)
49         if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
50                 return false
51         end
52         return true
53 end
54
55 --------------------------------------------------------------------------------
56 -- Dumps values in a line-per-value format.
57 -- For example, {test = {"Testing..."}} becomes:
58 --   _["test"] = {}
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.
63
64 function dump2(o, name, dumped)
65         name = name or "_"
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"]'
71         dumped = dumped or {}
72         if type(o) ~= "table" then
73                 return string.format("%s = %s\n", name, basic_dump(o))
74         end
75         if dumped[o] then
76                 return string.format("%s = %s\n", name, dumped[o])
77         end
78         dumped[o] = name
79         -- This contains a list of strings to be concatenated later (because
80         -- Lua is slow at individual concatenation).
81         local t = {}
82         for k, v in pairs(o) do
83                 local keyStr
84                 if type(k) == "table" then
85                         if dumped[k] then
86                                 keyStr = dumped[k]
87                         else
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))
91                                 -- Dump key table
92                                 table.insert(t, dump2(k, keyStr, dumped))
93                         end
94                 else
95                         keyStr = basic_dump(k)
96                 end
97                 local vname = string.format("%s[%s]", name, keyStr)
98                 table.insert(t, dump2(v, vname, dumped))
99         end
100         return string.format("%s = {}\n%s", name, table.concat(t))
101 end
102
103 --------------------------------------------------------------------------------
104 -- This dumps values in a one-statement format.
105 -- For example, {test = {"Testing..."}} becomes:
106 -- [[{
107 --      test = {
108 --              "Testing..."
109 --      }
110 -- }]]
111 -- This supports tables as keys, but not circular references.
112 -- It performs poorly with multiple references as it writes out the full
113 -- table each time.
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.
117
118 function dump(o, indent, nested, level)
119         if type(o) ~= "table" then
120                 return basic_dump(o)
121         end
122         -- Contains table -> true/nil of currently nested tables
123         nested = nested or {}
124         if nested[o] then
125                 return "<circular reference>"
126         end
127         nested[o] = true
128         indent = indent or "\t"
129         level = level or 1
130         local 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
135         end
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).."]"
140                         end
141                         v = dump(v, indent, nested, level + 1)
142                         table.insert(t, k.." = "..v)
143                 end
144         end
145         nested[o] = nil
146         if indent ~= "" then
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}",
150                                 indent_str,
151                                 table.concat(t, ","..indent_str),
152                                 end_indent_str)
153         end
154         return "{"..table.concat(t, ", ").."}"
155 end
156
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)
162         delim = delim or ","
163         max_splits = max_splits or -1
164         local items = {}
165         local pos, len, seplen = 1, #str, #delim
166         local plain = not sep_is_pattern
167         max_splits = max_splits + 1
168         repeat
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
172                         np = len + 1
173                         npe = np
174                 end
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)
179                 end
180                 pos = npe + 1
181         until (max_splits == 0) or (pos > (len + 1))
182         return items
183 end
184
185 --------------------------------------------------------------------------------
186 function file_exists(filename)
187         local f = io.open(filename, "r")
188         if f==nil then
189                 return false
190         else
191                 f:close()
192                 return true
193         end
194 end
195
196 --------------------------------------------------------------------------------
197 function string:trim()
198         return (self:gsub("^%s*(.-)%s*$", "%1"))
199 end
200
201 assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")
202
203 --------------------------------------------------------------------------------
204 function math.hypot(x, y)
205         local t
206         x = math.abs(x)
207         y = math.abs(y)
208         t = math.min(x, y)
209         x = math.max(x, y)
210         if x == 0 then return 0 end
211         t = t / x
212         return x * math.sqrt(1 + t * t)
213 end
214
215 --------------------------------------------------------------------------------
216 function math.sign(x, tolerance)
217         tolerance = tolerance or 0
218         if x > tolerance then
219                 return 1
220         elseif x < -tolerance then
221                 return -1
222         end
223         return 0
224 end
225
226 --------------------------------------------------------------------------------
227 function get_last_folder(text,count)
228         local parts = text:split(DIR_DELIM)
229
230         if count == nil then
231                 return parts[#parts]
232         end
233
234         local retval = ""
235         for i=1,count,1 do
236                 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
237         end
238
239         return retval
240 end
241
242 --------------------------------------------------------------------------------
243 function cleanup_path(temppath)
244
245         local parts = temppath:split("-")
246         temppath = ""
247         for i=1,#parts,1 do
248                 if temppath ~= "" then
249                         temppath = temppath .. "_"
250                 end
251                 temppath = temppath .. parts[i]
252         end
253
254         parts = temppath:split(".")
255         temppath = ""
256         for i=1,#parts,1 do
257                 if temppath ~= "" then
258                         temppath = temppath .. "_"
259                 end
260                 temppath = temppath .. parts[i]
261         end
262
263         parts = temppath:split("'")
264         temppath = ""
265         for i=1,#parts,1 do
266                 if temppath ~= "" then
267                         temppath = temppath .. ""
268                 end
269                 temppath = temppath .. parts[i]
270         end
271
272         parts = temppath:split(" ")
273         temppath = ""
274         for i=1,#parts,1 do
275                 if temppath ~= "" then
276                         temppath = temppath
277                 end
278                 temppath = temppath .. parts[i]
279         end
280
281         return temppath
282 end
283
284 function core.formspec_escape(text)
285         if text ~= nil then
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,",","\\,")
291         end
292         return text
293 end
294
295
296 function core.splittext(text,charlimit)
297         local retval = {}
298
299         local current_idx = 1
300
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
305                 start = nl_start
306                 stop = nl_stop
307                 gotnewline = true
308         end
309         local last_line = ""
310         while start ~= nil do
311                 if string.len(last_line) + (stop-start) > charlimit then
312                         table.insert(retval,last_line)
313                         last_line = ""
314                 end
315
316                 if last_line ~= "" then
317                         last_line = last_line .. " "
318                 end
319
320                 last_line = last_line .. string.sub(text,current_idx,stop -1)
321
322                 if gotnewline then
323                         table.insert(retval,last_line)
324                         last_line = ""
325                         gotnewline = false
326                 end
327                 current_idx = stop+1
328
329                 start,stop = string.find(text," ",current_idx)
330                 nl_start,nl_stop = string.find(text,"\n",current_idx)
331
332                 if nl_start ~= nil and (start == nil or nl_start < start) then
333                         start = nl_start
334                         stop = nl_stop
335                         gotnewline = true
336                 end
337         end
338
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))
343         else
344                 last_line = last_line .. " " .. string.sub(text,current_idx)
345                 table.insert(retval,last_line)
346         end
347
348         return retval
349 end
350
351 --------------------------------------------------------------------------------
352
353 if INIT == "game" then
354         local dirs1 = {9, 18, 7, 12}
355         local dirs2 = {20, 23, 22, 21}
356
357         function core.rotate_and_place(itemstack, placer, pointed_thing,
358                                 infinitestacks, orient_flags)
359                 orient_flags = orient_flags or {}
360
361                 local unode = core.get_node_or_nil(pointed_thing.under)
362                 if not unode then
363                         return
364                 end
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)
369                         return
370                 end
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()
374
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)
380                 if not anode then
381                         return
382                 end
383                 local pos = pointed_thing.above
384                 local node = anode
385
386                 if undef and undef.buildable_to then
387                         pos = pointed_thing.under
388                         node = unode
389                         iswall = false
390                 end
391
392                 if core.is_protected(pos, placer:get_player_name()) then
393                         core.record_protection_violation(pos,
394                                         placer:get_player_name())
395                         return
396                 end
397
398                 local ndef = core.registered_nodes[node.name]
399                 if not ndef or not ndef.buildable_to then
400                         return
401                 end
402
403                 if orient_flags.force_floor then
404                         iswall = false
405                         isceiling = false
406                 elseif orient_flags.force_ceiling then
407                         iswall = false
408                         isceiling = true
409                 elseif orient_flags.force_wall then
410                         iswall = true
411                         isceiling = false
412                 elseif orient_flags.invert_wall then
413                         iswall = not iswall
414                 end
415
416                 if iswall 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,
422                                                 param2 = 20})
423                         else
424                                 core.set_node(pos, {name = wield_name,
425                                                 param2 = dirs2[fdir+1]})
426                         end
427                 else -- place right side up
428                         if orient_flags.force_facedir then
429                                 core.set_node(pos, {name = wield_name,
430                                                 param2 = 0})
431                         else
432                                 core.set_node(pos, {name = wield_name,
433                                                 param2 = fdir})
434                         end
435                 end
436
437                 if not infinitestacks then
438                         itemstack:take_item()
439                         return itemstack
440                 end
441         end
442
443
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 --------------------------------------------------------------------------------
448
449
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})
454                 return itemstack
455         end
456 end
457
458 --------------------------------------------------------------------------------
459 function core.explode_table_event(evt)
460         if evt ~= nil then
461                 local parts = evt:split(":")
462                 if #parts == 3 then
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"
467                                         and t ~= "INV" then
468                                 return {type=t, row=r, column=c}
469                         end
470                 end
471         end
472         return {type="INV", row=0, column=0}
473 end
474
475 --------------------------------------------------------------------------------
476 function core.explode_textlist_event(evt)
477         if evt ~= nil then
478                 local parts = evt:split(":")
479                 if #parts == 2 then
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}
484                         end
485                 end
486         end
487         return {type="INV", index=0}
488 end
489
490 --------------------------------------------------------------------------------
491 function core.explode_scrollbar_event(evt)
492         local retval = core.explode_textlist_event(evt)
493
494         retval.value = retval.index
495         retval.index = nil
496
497         return retval
498 end
499
500 --------------------------------------------------------------------------------
501 function core.pos_to_string(pos, decimal_places)
502         local x = pos.x
503         local y = pos.y
504         local z = pos.z
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)
509         end
510         return "(" .. x .. "," .. y .. "," .. z .. ")"
511 end
512
513 --------------------------------------------------------------------------------
514 function core.string_to_pos(value)
515         if value == nil then
516                 return nil
517         end
518
519         local p = {}
520         p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
521         if p.x and p.y and p.z then
522                 p.x = tonumber(p.x)
523                 p.y = tonumber(p.y)
524                 p.z = tonumber(p.z)
525                 return p
526         end
527         local p = {}
528         p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
529         if p.x and p.y and p.z then
530                 p.x = tonumber(p.x)
531                 p.y = tonumber(p.y)
532                 p.z = tonumber(p.z)
533                 return p
534         end
535         return nil
536 end
537
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)
541
542 --------------------------------------------------------------------------------
543 function table.copy(t, seen)
544         local n = {}
545         seen = seen or {}
546         seen[t] = n
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)
550         end
551         return n
552 end
553
554 --------------------------------------------------------------------------------
555 -- mainmenu only functions
556 --------------------------------------------------------------------------------
557 if INIT == "mainmenu" then
558         function core.get_game(index)
559                 local games = game.get_games()
560
561                 if index > 0 and index <= #games then
562                         return games[index]
563                 end
564
565                 return nil
566         end
567
568         function fgettext(text, ...)
569                 text = core.gettext(text)
570                 local arg = {n=select('#', ...), ...}
571                 if arg.n >= 1 then
572                         -- Insert positional parameters ($1, $2, ...)
573                         local result = ''
574                         local pos = 1
575                         while pos <= text:len() do
576                                 local newpos = text:find('[$]', pos)
577                                 if newpos == nil then
578                                         result = result .. text:sub(pos)
579                                         pos = text:len() + 1
580                                 else
581                                         local paramindex =
582                                                 tonumber(text:sub(newpos+1, newpos+1))
583                                         result = result .. text:sub(pos, newpos-1)
584                                                 .. tostring(arg[paramindex])
585                                         pos = newpos + 2
586                                 end
587                         end
588                         text = result
589                 end
590                 return core.formspec_escape(text)
591         end
592 end
593