misc_helpers.lua 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. -- Minetest: builtin/misc_helpers.lua
  2. --------------------------------------------------------------------------------
  3. function basic_dump(o)
  4. local tp = type(o)
  5. if tp == "number" then
  6. return tostring(o)
  7. elseif tp == "string" then
  8. return string.format("%q", o)
  9. elseif tp == "boolean" then
  10. return tostring(o)
  11. elseif tp == "nil" then
  12. return "nil"
  13. -- Uncomment for full function dumping support.
  14. -- Not currently enabled because bytecode isn't very human-readable and
  15. -- dump's output is intended for humans.
  16. --elseif tp == "function" then
  17. -- return string.format("loadstring(%q)", string.dump(o))
  18. else
  19. return string.format("<%s>", tp)
  20. end
  21. end
  22. local keywords = {
  23. ["and"] = true,
  24. ["break"] = true,
  25. ["do"] = true,
  26. ["else"] = true,
  27. ["elseif"] = true,
  28. ["end"] = true,
  29. ["false"] = true,
  30. ["for"] = true,
  31. ["function"] = true,
  32. ["goto"] = true, -- Lua 5.2
  33. ["if"] = true,
  34. ["in"] = true,
  35. ["local"] = true,
  36. ["nil"] = true,
  37. ["not"] = true,
  38. ["or"] = true,
  39. ["repeat"] = true,
  40. ["return"] = true,
  41. ["then"] = true,
  42. ["true"] = true,
  43. ["until"] = true,
  44. ["while"] = true,
  45. }
  46. local function is_valid_identifier(str)
  47. if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
  48. return false
  49. end
  50. return true
  51. end
  52. --------------------------------------------------------------------------------
  53. -- Dumps values in a line-per-value format.
  54. -- For example, {test = {"Testing..."}} becomes:
  55. -- _["test"] = {}
  56. -- _["test"][1] = "Testing..."
  57. -- This handles tables as keys and circular references properly.
  58. -- It also handles multiple references well, writing the table only once.
  59. -- The dumped argument is internal-only.
  60. function dump2(o, name, dumped)
  61. name = name or "_"
  62. -- "dumped" is used to keep track of serialized tables to handle
  63. -- multiple references and circular tables properly.
  64. -- It only contains tables as keys. The value is the name that
  65. -- the table has in the dump, eg:
  66. -- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
  67. dumped = dumped or {}
  68. if type(o) ~= "table" then
  69. return string.format("%s = %s\n", name, basic_dump(o))
  70. end
  71. if dumped[o] then
  72. return string.format("%s = %s\n", name, dumped[o])
  73. end
  74. dumped[o] = name
  75. -- This contains a list of strings to be concatenated later (because
  76. -- Lua is slow at individual concatenation).
  77. local t = {}
  78. for k, v in pairs(o) do
  79. local keyStr
  80. if type(k) == "table" then
  81. if dumped[k] then
  82. keyStr = dumped[k]
  83. else
  84. -- Key tables don't have a name, so use one of
  85. -- the form _G["table: 0xFFFFFFF"]
  86. keyStr = string.format("_G[%q]", tostring(k))
  87. -- Dump key table
  88. table.insert(t, dump2(k, keyStr, dumped))
  89. end
  90. else
  91. keyStr = basic_dump(k)
  92. end
  93. local vname = string.format("%s[%s]", name, keyStr)
  94. table.insert(t, dump2(v, vname, dumped))
  95. end
  96. return string.format("%s = {}\n%s", name, table.concat(t))
  97. end
  98. --------------------------------------------------------------------------------
  99. -- This dumps values in a one-statement format.
  100. -- For example, {test = {"Testing..."}} becomes:
  101. -- [[{
  102. -- test = {
  103. -- "Testing..."
  104. -- }
  105. -- }]]
  106. -- This supports tables as keys, but not circular references.
  107. -- It performs poorly with multiple references as it writes out the full
  108. -- table each time.
  109. -- The indent field specifies a indentation string, it defaults to a tab.
  110. -- Use the empty string to disable indentation.
  111. -- The dumped and level arguments are internal-only.
  112. function dump(o, indent, nested, level)
  113. if type(o) ~= "table" then
  114. return basic_dump(o)
  115. end
  116. -- Contains table -> true/nil of currently nested tables
  117. nested = nested or {}
  118. if nested[o] then
  119. return "<circular reference>"
  120. end
  121. nested[o] = true
  122. indent = indent or "\t"
  123. level = level or 1
  124. local t = {}
  125. local dumped_indexes = {}
  126. for i, v in ipairs(o) do
  127. table.insert(t, dump(v, indent, nested, level + 1))
  128. dumped_indexes[i] = true
  129. end
  130. for k, v in pairs(o) do
  131. if not dumped_indexes[k] then
  132. if type(k) ~= "string" or not is_valid_identifier(k) then
  133. k = "["..dump(k, indent, nested, level + 1).."]"
  134. end
  135. v = dump(v, indent, nested, level + 1)
  136. table.insert(t, k.." = "..v)
  137. end
  138. end
  139. nested[o] = nil
  140. if indent ~= "" then
  141. local indent_str = "\n"..string.rep(indent, level)
  142. local end_indent_str = "\n"..string.rep(indent, level - 1)
  143. return string.format("{%s%s%s}",
  144. indent_str,
  145. table.concat(t, ","..indent_str),
  146. end_indent_str)
  147. end
  148. return "{"..table.concat(t, ", ").."}"
  149. end
  150. --------------------------------------------------------------------------------
  151. -- Localize functions to avoid table lookups (better performance).
  152. local table_insert = table.insert
  153. local str_sub, str_find = string.sub, string.find
  154. function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
  155. delim = delim or ","
  156. max_splits = max_splits or -1
  157. local items = {}
  158. local pos, len, seplen = 1, #str, #delim
  159. local plain = not sep_is_pattern
  160. max_splits = max_splits + 1
  161. repeat
  162. local np, npe = str_find(str, delim, pos, plain)
  163. np, npe = (np or (len+1)), (npe or (len+1))
  164. if (not np) or (max_splits == 1) then
  165. np = len + 1
  166. npe = np
  167. end
  168. local s = str_sub(str, pos, np - 1)
  169. if include_empty or (s ~= "") then
  170. max_splits = max_splits - 1
  171. table_insert(items, s)
  172. end
  173. pos = npe + 1
  174. until (max_splits == 0) or (pos > (len + 1))
  175. return items
  176. end
  177. --------------------------------------------------------------------------------
  178. function file_exists(filename)
  179. local f = io.open(filename, "r")
  180. if f==nil then
  181. return false
  182. else
  183. f:close()
  184. return true
  185. end
  186. end
  187. --------------------------------------------------------------------------------
  188. function string:trim()
  189. return (self:gsub("^%s*(.-)%s*$", "%1"))
  190. end
  191. assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")
  192. --------------------------------------------------------------------------------
  193. function math.hypot(x, y)
  194. local t
  195. x = math.abs(x)
  196. y = math.abs(y)
  197. t = math.min(x, y)
  198. x = math.max(x, y)
  199. if x == 0 then return 0 end
  200. t = t / x
  201. return x * math.sqrt(1 + t * t)
  202. end
  203. --------------------------------------------------------------------------------
  204. function math.sign(x, tolerance)
  205. tolerance = tolerance or 0
  206. if x > tolerance then
  207. return 1
  208. elseif x < -tolerance then
  209. return -1
  210. end
  211. return 0
  212. end
  213. --------------------------------------------------------------------------------
  214. function get_last_folder(text,count)
  215. local parts = text:split(DIR_DELIM)
  216. if count == nil then
  217. return parts[#parts]
  218. end
  219. local retval = ""
  220. for i=1,count,1 do
  221. retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
  222. end
  223. return retval
  224. end
  225. --------------------------------------------------------------------------------
  226. function cleanup_path(temppath)
  227. local parts = temppath:split("-")
  228. temppath = ""
  229. for i=1,#parts,1 do
  230. if temppath ~= "" then
  231. temppath = temppath .. "_"
  232. end
  233. temppath = temppath .. parts[i]
  234. end
  235. parts = temppath:split(".")
  236. temppath = ""
  237. for i=1,#parts,1 do
  238. if temppath ~= "" then
  239. temppath = temppath .. "_"
  240. end
  241. temppath = temppath .. parts[i]
  242. end
  243. parts = temppath:split("'")
  244. temppath = ""
  245. for i=1,#parts,1 do
  246. if temppath ~= "" then
  247. temppath = temppath .. ""
  248. end
  249. temppath = temppath .. parts[i]
  250. end
  251. parts = temppath:split(" ")
  252. temppath = ""
  253. for i=1,#parts,1 do
  254. if temppath ~= "" then
  255. temppath = temppath
  256. end
  257. temppath = temppath .. parts[i]
  258. end
  259. return temppath
  260. end
  261. function core.formspec_escape(text)
  262. if text ~= nil then
  263. text = string.gsub(text,"\\","\\\\")
  264. text = string.gsub(text,"%]","\\]")
  265. text = string.gsub(text,"%[","\\[")
  266. text = string.gsub(text,";","\\;")
  267. text = string.gsub(text,",","\\,")
  268. end
  269. return text
  270. end
  271. function core.splittext(text,charlimit)
  272. local retval = {}
  273. local current_idx = 1
  274. local start,stop = string.find(text," ",current_idx)
  275. local nl_start,nl_stop = string.find(text,"\n",current_idx)
  276. local gotnewline = false
  277. if nl_start ~= nil and (start == nil or nl_start < start) then
  278. start = nl_start
  279. stop = nl_stop
  280. gotnewline = true
  281. end
  282. local last_line = ""
  283. while start ~= nil do
  284. if string.len(last_line) + (stop-start) > charlimit then
  285. table.insert(retval,last_line)
  286. last_line = ""
  287. end
  288. if last_line ~= "" then
  289. last_line = last_line .. " "
  290. end
  291. last_line = last_line .. string.sub(text,current_idx,stop -1)
  292. if gotnewline then
  293. table.insert(retval,last_line)
  294. last_line = ""
  295. gotnewline = false
  296. end
  297. current_idx = stop+1
  298. start,stop = string.find(text," ",current_idx)
  299. nl_start,nl_stop = string.find(text,"\n",current_idx)
  300. if nl_start ~= nil and (start == nil or nl_start < start) then
  301. start = nl_start
  302. stop = nl_stop
  303. gotnewline = true
  304. end
  305. end
  306. --add last part of text
  307. if string.len(last_line) + (string.len(text) - current_idx) > charlimit then
  308. table.insert(retval,last_line)
  309. table.insert(retval,string.sub(text,current_idx))
  310. else
  311. last_line = last_line .. " " .. string.sub(text,current_idx)
  312. table.insert(retval,last_line)
  313. end
  314. return retval
  315. end
  316. --------------------------------------------------------------------------------
  317. if INIT == "game" then
  318. local dirs1 = {9, 18, 7, 12}
  319. local dirs2 = {20, 23, 22, 21}
  320. function core.rotate_and_place(itemstack, placer, pointed_thing,
  321. infinitestacks, orient_flags)
  322. orient_flags = orient_flags or {}
  323. local unode = core.get_node_or_nil(pointed_thing.under)
  324. if not unode then
  325. return
  326. end
  327. local undef = core.registered_nodes[unode.name]
  328. if undef and undef.on_rightclick then
  329. undef.on_rightclick(pointed_thing.under, unode, placer,
  330. itemstack, pointed_thing)
  331. return
  332. end
  333. local pitch = placer:get_look_pitch()
  334. local fdir = core.dir_to_facedir(placer:get_look_dir())
  335. local wield_name = itemstack:get_name()
  336. local above = pointed_thing.above
  337. local under = pointed_thing.under
  338. local iswall = (above.y == under.y)
  339. local isceiling = not iswall and (above.y < under.y)
  340. local anode = core.get_node_or_nil(above)
  341. if not anode then
  342. return
  343. end
  344. local pos = pointed_thing.above
  345. local node = anode
  346. if undef and undef.buildable_to then
  347. pos = pointed_thing.under
  348. node = unode
  349. iswall = false
  350. end
  351. if core.is_protected(pos, placer:get_player_name()) then
  352. core.record_protection_violation(pos,
  353. placer:get_player_name())
  354. return
  355. end
  356. local ndef = core.registered_nodes[node.name]
  357. if not ndef or not ndef.buildable_to then
  358. return
  359. end
  360. if orient_flags.force_floor then
  361. iswall = false
  362. isceiling = false
  363. elseif orient_flags.force_ceiling then
  364. iswall = false
  365. isceiling = true
  366. elseif orient_flags.force_wall then
  367. iswall = true
  368. isceiling = false
  369. elseif orient_flags.invert_wall then
  370. iswall = not iswall
  371. end
  372. if iswall then
  373. core.set_node(pos, {name = wield_name,
  374. param2 = dirs1[fdir+1]})
  375. elseif isceiling then
  376. if orient_flags.force_facedir then
  377. core.set_node(pos, {name = wield_name,
  378. param2 = 20})
  379. else
  380. core.set_node(pos, {name = wield_name,
  381. param2 = dirs2[fdir+1]})
  382. end
  383. else -- place right side up
  384. if orient_flags.force_facedir then
  385. core.set_node(pos, {name = wield_name,
  386. param2 = 0})
  387. else
  388. core.set_node(pos, {name = wield_name,
  389. param2 = fdir})
  390. end
  391. end
  392. if not infinitestacks then
  393. itemstack:take_item()
  394. return itemstack
  395. end
  396. end
  397. --------------------------------------------------------------------------------
  398. --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
  399. --implies infinite stacks when performing a 6d rotation.
  400. --------------------------------------------------------------------------------
  401. core.rotate_node = function(itemstack, placer, pointed_thing)
  402. core.rotate_and_place(itemstack, placer, pointed_thing,
  403. core.setting_getbool("creative_mode"),
  404. {invert_wall = placer:get_player_control().sneak})
  405. return itemstack
  406. end
  407. end
  408. --------------------------------------------------------------------------------
  409. function core.explode_table_event(evt)
  410. if evt ~= nil then
  411. local parts = evt:split(":")
  412. if #parts == 3 then
  413. local t = parts[1]:trim()
  414. local r = tonumber(parts[2]:trim())
  415. local c = tonumber(parts[3]:trim())
  416. if type(r) == "number" and type(c) == "number"
  417. and t ~= "INV" then
  418. return {type=t, row=r, column=c}
  419. end
  420. end
  421. end
  422. return {type="INV", row=0, column=0}
  423. end
  424. --------------------------------------------------------------------------------
  425. function core.explode_textlist_event(evt)
  426. if evt ~= nil then
  427. local parts = evt:split(":")
  428. if #parts == 2 then
  429. local t = parts[1]:trim()
  430. local r = tonumber(parts[2]:trim())
  431. if type(r) == "number" and t ~= "INV" then
  432. return {type=t, index=r}
  433. end
  434. end
  435. end
  436. return {type="INV", index=0}
  437. end
  438. --------------------------------------------------------------------------------
  439. function core.explode_scrollbar_event(evt)
  440. local retval = core.explode_textlist_event(evt)
  441. retval.value = retval.index
  442. retval.index = nil
  443. return retval
  444. end
  445. --------------------------------------------------------------------------------
  446. function core.pos_to_string(pos, decimal_places)
  447. local x = pos.x
  448. local y = pos.y
  449. local z = pos.z
  450. if decimal_places ~= nil then
  451. x = string.format("%." .. decimal_places .. "f", x)
  452. y = string.format("%." .. decimal_places .. "f", y)
  453. z = string.format("%." .. decimal_places .. "f", z)
  454. end
  455. return "(" .. x .. "," .. y .. "," .. z .. ")"
  456. end
  457. --------------------------------------------------------------------------------
  458. function core.string_to_pos(value)
  459. if value == nil then
  460. return nil
  461. end
  462. local p = {}
  463. p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
  464. if p.x and p.y and p.z then
  465. p.x = tonumber(p.x)
  466. p.y = tonumber(p.y)
  467. p.z = tonumber(p.z)
  468. return p
  469. end
  470. local p = {}
  471. p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
  472. if p.x and p.y and p.z then
  473. p.x = tonumber(p.x)
  474. p.y = tonumber(p.y)
  475. p.z = tonumber(p.z)
  476. return p
  477. end
  478. return nil
  479. end
  480. assert(core.string_to_pos("10.0, 5, -2").x == 10)
  481. assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
  482. assert(core.string_to_pos("asd, 5, -2)") == nil)
  483. --------------------------------------------------------------------------------
  484. function table.copy(t, seen)
  485. local n = {}
  486. seen = seen or {}
  487. seen[t] = n
  488. for k, v in pairs(t) do
  489. n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
  490. (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
  491. end
  492. return n
  493. end
  494. --------------------------------------------------------------------------------
  495. -- mainmenu only functions
  496. --------------------------------------------------------------------------------
  497. if INIT == "mainmenu" then
  498. function core.get_game(index)
  499. local games = game.get_games()
  500. if index > 0 and index <= #games then
  501. return games[index]
  502. end
  503. return nil
  504. end
  505. function fgettext_ne(text, ...)
  506. text = core.gettext(text)
  507. local arg = {n=select('#', ...), ...}
  508. if arg.n >= 1 then
  509. -- Insert positional parameters ($1, $2, ...)
  510. local result = ''
  511. local pos = 1
  512. while pos <= text:len() do
  513. local newpos = text:find('[$]', pos)
  514. if newpos == nil then
  515. result = result .. text:sub(pos)
  516. pos = text:len() + 1
  517. else
  518. local paramindex =
  519. tonumber(text:sub(newpos+1, newpos+1))
  520. result = result .. text:sub(pos, newpos-1)
  521. .. tostring(arg[paramindex])
  522. pos = newpos + 2
  523. end
  524. end
  525. text = result
  526. end
  527. return text
  528. end
  529. function fgettext(text, ...)
  530. return core.formspec_escape(fgettext_ne(text, ...))
  531. end
  532. end