misc_helpers.lua 16 KB

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