misc_helpers.lua 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. -- Minetest: builtin/misc_helpers.lua
  2. --------------------------------------------------------------------------------
  3. -- Localize functions to avoid table lookups (better performance).
  4. local string_sub, string_find = string.sub, string.find
  5. --------------------------------------------------------------------------------
  6. local function basic_dump(o)
  7. local tp = type(o)
  8. if tp == "number" then
  9. return tostring(o)
  10. elseif tp == "string" then
  11. return string.format("%q", o)
  12. elseif tp == "boolean" then
  13. return tostring(o)
  14. elseif tp == "nil" then
  15. return "nil"
  16. -- Uncomment for full function dumping support.
  17. -- Not currently enabled because bytecode isn't very human-readable and
  18. -- dump's output is intended for humans.
  19. --elseif tp == "function" then
  20. -- return string.format("loadstring(%q)", string.dump(o))
  21. elseif tp == "userdata" then
  22. return tostring(o)
  23. else
  24. return string.format("<%s>", tp)
  25. end
  26. end
  27. local keywords = {
  28. ["and"] = true,
  29. ["break"] = true,
  30. ["do"] = true,
  31. ["else"] = true,
  32. ["elseif"] = true,
  33. ["end"] = true,
  34. ["false"] = true,
  35. ["for"] = true,
  36. ["function"] = true,
  37. ["goto"] = true, -- Lua 5.2
  38. ["if"] = true,
  39. ["in"] = true,
  40. ["local"] = true,
  41. ["nil"] = true,
  42. ["not"] = true,
  43. ["or"] = true,
  44. ["repeat"] = true,
  45. ["return"] = true,
  46. ["then"] = true,
  47. ["true"] = true,
  48. ["until"] = true,
  49. ["while"] = true,
  50. }
  51. local function is_valid_identifier(str)
  52. if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
  53. return false
  54. end
  55. return true
  56. end
  57. --------------------------------------------------------------------------------
  58. -- Dumps values in a line-per-value format.
  59. -- For example, {test = {"Testing..."}} becomes:
  60. -- _["test"] = {}
  61. -- _["test"][1] = "Testing..."
  62. -- This handles tables as keys and circular references properly.
  63. -- It also handles multiple references well, writing the table only once.
  64. -- The dumped argument is internal-only.
  65. function dump2(o, name, dumped)
  66. name = name or "_"
  67. -- "dumped" is used to keep track of serialized tables to handle
  68. -- multiple references and circular tables properly.
  69. -- It only contains tables as keys. The value is the name that
  70. -- the table has in the dump, eg:
  71. -- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
  72. dumped = dumped or {}
  73. if type(o) ~= "table" then
  74. return string.format("%s = %s\n", name, basic_dump(o))
  75. end
  76. if dumped[o] then
  77. return string.format("%s = %s\n", name, dumped[o])
  78. end
  79. dumped[o] = name
  80. -- This contains a list of strings to be concatenated later (because
  81. -- Lua is slow at individual concatenation).
  82. local t = {}
  83. for k, v in pairs(o) do
  84. local keyStr
  85. if type(k) == "table" then
  86. if dumped[k] then
  87. keyStr = dumped[k]
  88. else
  89. -- Key tables don't have a name, so use one of
  90. -- the form _G["table: 0xFFFFFFF"]
  91. keyStr = string.format("_G[%q]", tostring(k))
  92. -- Dump key table
  93. t[#t + 1] = dump2(k, keyStr, dumped)
  94. end
  95. else
  96. keyStr = basic_dump(k)
  97. end
  98. local vname = string.format("%s[%s]", name, keyStr)
  99. t[#t + 1] = dump2(v, vname, dumped)
  100. end
  101. return string.format("%s = {}\n%s", name, table.concat(t))
  102. end
  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. function dump(o, indent, nested, level)
  118. local t = type(o)
  119. if not level and t == "userdata" then
  120. -- when userdata (e.g. player) is passed directly, print its metatable:
  121. return "userdata metatable: " .. dump(getmetatable(o))
  122. end
  123. if t ~= "table" then
  124. return basic_dump(o)
  125. end
  126. -- Contains table -> true/nil of currently nested tables
  127. nested = nested or {}
  128. if nested[o] then
  129. return "<circular reference>"
  130. end
  131. nested[o] = true
  132. indent = indent or "\t"
  133. level = level or 1
  134. local ret = {}
  135. local dumped_indexes = {}
  136. for i, v in ipairs(o) do
  137. ret[#ret + 1] = dump(v, indent, nested, level + 1)
  138. dumped_indexes[i] = true
  139. end
  140. for k, v in pairs(o) do
  141. if not dumped_indexes[k] then
  142. if type(k) ~= "string" or not is_valid_identifier(k) then
  143. k = "["..dump(k, indent, nested, level + 1).."]"
  144. end
  145. v = dump(v, indent, nested, level + 1)
  146. ret[#ret + 1] = k.." = "..v
  147. end
  148. end
  149. nested[o] = nil
  150. if indent ~= "" then
  151. local indent_str = "\n"..string.rep(indent, level)
  152. local end_indent_str = "\n"..string.rep(indent, level - 1)
  153. return string.format("{%s%s%s}",
  154. indent_str,
  155. table.concat(ret, ","..indent_str),
  156. end_indent_str)
  157. end
  158. return "{"..table.concat(ret, ", ").."}"
  159. end
  160. --------------------------------------------------------------------------------
  161. function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
  162. delim = delim or ","
  163. max_splits = max_splits or -2
  164. local items = {}
  165. local pos, len = 1, #str
  166. local plain = not sep_is_pattern
  167. max_splits = max_splits + 1
  168. repeat
  169. local np, npe = string_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 = string_sub(str, pos, np - 1)
  176. if include_empty or (s ~= "") then
  177. max_splits = max_splits - 1
  178. items[#items + 1] = s
  179. end
  180. pos = npe + 1
  181. until (max_splits == 0) or (pos > (len + 1))
  182. return items
  183. end
  184. --------------------------------------------------------------------------------
  185. function table.indexof(list, val)
  186. for i, v in ipairs(list) do
  187. if v == val then
  188. return i
  189. end
  190. end
  191. return -1
  192. end
  193. --------------------------------------------------------------------------------
  194. function string:trim()
  195. return self:match("^%s*(.-)%s*$")
  196. end
  197. --------------------------------------------------------------------------------
  198. function math.hypot(x, y)
  199. return math.sqrt(x * x + y * y)
  200. end
  201. --------------------------------------------------------------------------------
  202. function math.sign(x, tolerance)
  203. tolerance = tolerance or 0
  204. if x > tolerance then
  205. return 1
  206. elseif x < -tolerance then
  207. return -1
  208. end
  209. return 0
  210. end
  211. --------------------------------------------------------------------------------
  212. function math.factorial(x)
  213. assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
  214. if x >= 171 then
  215. -- 171! is greater than the biggest double, no need to calculate
  216. return math.huge
  217. end
  218. local v = 1
  219. for k = 2, x do
  220. v = v * k
  221. end
  222. return v
  223. end
  224. function math.round(x)
  225. if x >= 0 then
  226. return math.floor(x + 0.5)
  227. end
  228. return math.ceil(x - 0.5)
  229. end
  230. local formspec_escapes = {
  231. ["\\"] = "\\\\",
  232. ["["] = "\\[",
  233. ["]"] = "\\]",
  234. [";"] = "\\;",
  235. [","] = "\\,"
  236. }
  237. function core.formspec_escape(text)
  238. -- Use explicit character set instead of dot here because it doubles the performance
  239. return text and string.gsub(text, "[\\%[%];,]", formspec_escapes)
  240. end
  241. function core.wrap_text(text, max_length, as_table)
  242. local result = {}
  243. local line = {}
  244. if #text <= max_length then
  245. return as_table and {text} or text
  246. end
  247. local line_length = 0
  248. for word in text:gmatch("%S+") do
  249. if line_length > 0 and line_length + #word + 1 >= max_length then
  250. -- word wouldn't fit on current line, move to next line
  251. table.insert(result, table.concat(line, " "))
  252. line = {word}
  253. line_length = #word
  254. else
  255. table.insert(line, word)
  256. line_length = line_length + 1 + #word
  257. end
  258. end
  259. table.insert(result, table.concat(line, " "))
  260. return as_table and result or table.concat(result, "\n")
  261. end
  262. --------------------------------------------------------------------------------
  263. if INIT == "game" then
  264. local dirs1 = {9, 18, 7, 12}
  265. local dirs2 = {20, 23, 22, 21}
  266. function core.rotate_and_place(itemstack, placer, pointed_thing,
  267. infinitestacks, orient_flags, prevent_after_place)
  268. orient_flags = orient_flags or {}
  269. local unode = core.get_node_or_nil(pointed_thing.under)
  270. if not unode then
  271. return
  272. end
  273. local undef = core.registered_nodes[unode.name]
  274. local sneaking = placer and placer:get_player_control().sneak
  275. if undef and undef.on_rightclick and not sneaking then
  276. return undef.on_rightclick(pointed_thing.under, unode, placer,
  277. itemstack, pointed_thing)
  278. end
  279. local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
  280. local above = pointed_thing.above
  281. local under = pointed_thing.under
  282. local iswall = (above.y == under.y)
  283. local isceiling = not iswall and (above.y < under.y)
  284. if undef and undef.buildable_to then
  285. iswall = false
  286. end
  287. if orient_flags.force_floor then
  288. iswall = false
  289. isceiling = false
  290. elseif orient_flags.force_ceiling then
  291. iswall = false
  292. isceiling = true
  293. elseif orient_flags.force_wall then
  294. iswall = true
  295. isceiling = false
  296. elseif orient_flags.invert_wall then
  297. iswall = not iswall
  298. end
  299. local param2 = fdir
  300. if iswall then
  301. param2 = dirs1[fdir + 1]
  302. elseif isceiling then
  303. if orient_flags.force_facedir then
  304. param2 = 20
  305. else
  306. param2 = dirs2[fdir + 1]
  307. end
  308. else -- place right side up
  309. if orient_flags.force_facedir then
  310. param2 = 0
  311. end
  312. end
  313. local old_itemstack = ItemStack(itemstack)
  314. local new_itemstack = core.item_place_node(itemstack, placer,
  315. pointed_thing, param2, prevent_after_place)
  316. return infinitestacks and old_itemstack or new_itemstack
  317. end
  318. --------------------------------------------------------------------------------
  319. --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
  320. --implies infinite stacks when performing a 6d rotation.
  321. --------------------------------------------------------------------------------
  322. core.rotate_node = function(itemstack, placer, pointed_thing)
  323. local name = placer and placer:get_player_name() or ""
  324. local invert_wall = placer and placer:get_player_control().sneak or false
  325. return core.rotate_and_place(itemstack, placer, pointed_thing,
  326. core.is_creative_enabled(name),
  327. {invert_wall = invert_wall}, true)
  328. end
  329. end
  330. --------------------------------------------------------------------------------
  331. function core.explode_table_event(evt)
  332. if evt ~= nil then
  333. local parts = evt:split(":")
  334. if #parts == 3 then
  335. local t = parts[1]:trim()
  336. local r = tonumber(parts[2]:trim())
  337. local c = tonumber(parts[3]:trim())
  338. if type(r) == "number" and type(c) == "number"
  339. and t ~= "INV" then
  340. return {type=t, row=r, column=c}
  341. end
  342. end
  343. end
  344. return {type="INV", row=0, column=0}
  345. end
  346. --------------------------------------------------------------------------------
  347. function core.explode_textlist_event(evt)
  348. if evt ~= nil then
  349. local parts = evt:split(":")
  350. if #parts == 2 then
  351. local t = parts[1]:trim()
  352. local r = tonumber(parts[2]:trim())
  353. if type(r) == "number" and t ~= "INV" then
  354. return {type=t, index=r}
  355. end
  356. end
  357. end
  358. return {type="INV", index=0}
  359. end
  360. --------------------------------------------------------------------------------
  361. function core.explode_scrollbar_event(evt)
  362. local retval = core.explode_textlist_event(evt)
  363. retval.value = retval.index
  364. retval.index = nil
  365. return retval
  366. end
  367. --------------------------------------------------------------------------------
  368. function core.rgba(r, g, b, a)
  369. return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
  370. string.format("#%02X%02X%02X", r, g, b)
  371. end
  372. --------------------------------------------------------------------------------
  373. function core.pos_to_string(pos, decimal_places)
  374. local x = pos.x
  375. local y = pos.y
  376. local z = pos.z
  377. if decimal_places ~= nil then
  378. x = string.format("%." .. decimal_places .. "f", x)
  379. y = string.format("%." .. decimal_places .. "f", y)
  380. z = string.format("%." .. decimal_places .. "f", z)
  381. end
  382. return "(" .. x .. "," .. y .. "," .. z .. ")"
  383. end
  384. --------------------------------------------------------------------------------
  385. function core.string_to_pos(value)
  386. if value == nil then
  387. return nil
  388. end
  389. value = value:match("^%((.-)%)$") or value -- strip parentheses
  390. local x, y, z = value:trim():match("^([%d.-]+)[,%s]%s*([%d.-]+)[,%s]%s*([%d.-]+)$")
  391. if x and y and z then
  392. x = tonumber(x)
  393. y = tonumber(y)
  394. z = tonumber(z)
  395. return vector.new(x, y, z)
  396. end
  397. return nil
  398. end
  399. --------------------------------------------------------------------------------
  400. do
  401. local rel_num_cap = "(~?-?%d*%.?%d*)" -- may be overly permissive as this will be tonumber'ed anyways
  402. local num_delim = "[,%s]%s*"
  403. local pattern = "^" .. table.concat({rel_num_cap, rel_num_cap, rel_num_cap}, num_delim) .. "$"
  404. local function parse_area_string(pos, relative_to)
  405. local pp = {}
  406. pp.x, pp.y, pp.z = pos:trim():match(pattern)
  407. return core.parse_coordinates(pp.x, pp.y, pp.z, relative_to)
  408. end
  409. function core.string_to_area(value, relative_to)
  410. local p1, p2 = value:match("^%((.-)%)%s*%((.-)%)$")
  411. if not p1 then
  412. return
  413. end
  414. p1 = parse_area_string(p1, relative_to)
  415. p2 = parse_area_string(p2, relative_to)
  416. if p1 == nil or p2 == nil then
  417. return
  418. end
  419. return p1, p2
  420. end
  421. end
  422. --------------------------------------------------------------------------------
  423. function table.copy(t, seen)
  424. local n = {}
  425. seen = seen or {}
  426. seen[t] = n
  427. for k, v in pairs(t) do
  428. n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
  429. (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
  430. end
  431. return n
  432. end
  433. function table.insert_all(t, other)
  434. for i=1, #other do
  435. t[#t + 1] = other[i]
  436. end
  437. return t
  438. end
  439. function table.key_value_swap(t)
  440. local ti = {}
  441. for k,v in pairs(t) do
  442. ti[v] = k
  443. end
  444. return ti
  445. end
  446. function table.shuffle(t, from, to, random)
  447. from = from or 1
  448. to = to or #t
  449. random = random or math.random
  450. local n = to - from + 1
  451. while n > 1 do
  452. local r = from + n-1
  453. local l = from + random(0, n-1)
  454. t[l], t[r] = t[r], t[l]
  455. n = n-1
  456. end
  457. end
  458. --------------------------------------------------------------------------------
  459. -- mainmenu only functions
  460. --------------------------------------------------------------------------------
  461. if INIT == "mainmenu" then
  462. function core.get_game(index)
  463. local games = core.get_games()
  464. if index > 0 and index <= #games then
  465. return games[index]
  466. end
  467. return nil
  468. end
  469. end
  470. if core.gettext then -- for client and mainmenu
  471. function fgettext_ne(text, ...)
  472. text = core.gettext(text)
  473. local arg = {n=select('#', ...), ...}
  474. if arg.n >= 1 then
  475. -- Insert positional parameters ($1, $2, ...)
  476. local result = ''
  477. local pos = 1
  478. while pos <= text:len() do
  479. local newpos = text:find('[$]', pos)
  480. if newpos == nil then
  481. result = result .. text:sub(pos)
  482. pos = text:len() + 1
  483. else
  484. local paramindex =
  485. tonumber(text:sub(newpos+1, newpos+1))
  486. result = result .. text:sub(pos, newpos-1)
  487. .. tostring(arg[paramindex])
  488. pos = newpos + 2
  489. end
  490. end
  491. text = result
  492. end
  493. return text
  494. end
  495. function fgettext(text, ...)
  496. return core.formspec_escape(fgettext_ne(text, ...))
  497. end
  498. end
  499. local ESCAPE_CHAR = string.char(0x1b)
  500. function core.get_color_escape_sequence(color)
  501. return ESCAPE_CHAR .. "(c@" .. color .. ")"
  502. end
  503. function core.get_background_escape_sequence(color)
  504. return ESCAPE_CHAR .. "(b@" .. color .. ")"
  505. end
  506. function core.colorize(color, message)
  507. local lines = tostring(message):split("\n", true)
  508. local color_code = core.get_color_escape_sequence(color)
  509. for i, line in ipairs(lines) do
  510. lines[i] = color_code .. line
  511. end
  512. return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
  513. end
  514. function core.strip_foreground_colors(str)
  515. return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
  516. end
  517. function core.strip_background_colors(str)
  518. return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
  519. end
  520. function core.strip_colors(str)
  521. return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
  522. end
  523. function core.translate(textdomain, str, ...)
  524. local start_seq
  525. if textdomain == "" then
  526. start_seq = ESCAPE_CHAR .. "T"
  527. else
  528. start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
  529. end
  530. local arg = {n=select('#', ...), ...}
  531. local end_seq = ESCAPE_CHAR .. "E"
  532. local arg_index = 1
  533. local translated = str:gsub("@(.)", function(matched)
  534. local c = string.byte(matched)
  535. if string.byte("1") <= c and c <= string.byte("9") then
  536. local a = c - string.byte("0")
  537. if a ~= arg_index then
  538. error("Escape sequences in string given to core.translate " ..
  539. "are not in the correct order: got @" .. matched ..
  540. "but expected @" .. tostring(arg_index))
  541. end
  542. if a > arg.n then
  543. error("Not enough arguments provided to core.translate")
  544. end
  545. arg_index = arg_index + 1
  546. return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
  547. elseif matched == "n" then
  548. return "\n"
  549. else
  550. return matched
  551. end
  552. end)
  553. if arg_index < arg.n + 1 then
  554. error("Too many arguments provided to core.translate")
  555. end
  556. return start_seq .. translated .. end_seq
  557. end
  558. function core.get_translator(textdomain)
  559. return function(str, ...) return core.translate(textdomain or "", str, ...) end
  560. end
  561. --------------------------------------------------------------------------------
  562. -- Returns the exact coordinate of a pointed surface
  563. --------------------------------------------------------------------------------
  564. function core.pointed_thing_to_face_pos(placer, pointed_thing)
  565. -- Avoid crash in some situations when player is inside a node, causing
  566. -- 'above' to equal 'under'.
  567. if vector.equals(pointed_thing.above, pointed_thing.under) then
  568. return pointed_thing.under
  569. end
  570. local eye_height = placer:get_properties().eye_height
  571. local eye_offset_first = placer:get_eye_offset()
  572. local node_pos = pointed_thing.under
  573. local camera_pos = placer:get_pos()
  574. local pos_off = vector.multiply(
  575. vector.subtract(pointed_thing.above, node_pos), 0.5)
  576. local look_dir = placer:get_look_dir()
  577. local offset, nc
  578. local oc = {}
  579. for c, v in pairs(pos_off) do
  580. if nc or v == 0 then
  581. oc[#oc + 1] = c
  582. else
  583. offset = v
  584. nc = c
  585. end
  586. end
  587. local fine_pos = {[nc] = node_pos[nc] + offset}
  588. camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
  589. local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
  590. for i = 1, #oc do
  591. fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
  592. end
  593. return fine_pos
  594. end
  595. function core.string_to_privs(str, delim)
  596. assert(type(str) == "string")
  597. delim = delim or ','
  598. local privs = {}
  599. for _, priv in pairs(string.split(str, delim)) do
  600. privs[priv:trim()] = true
  601. end
  602. return privs
  603. end
  604. function core.privs_to_string(privs, delim)
  605. assert(type(privs) == "table")
  606. delim = delim or ','
  607. local list = {}
  608. for priv, bool in pairs(privs) do
  609. if bool then
  610. list[#list + 1] = priv
  611. end
  612. end
  613. return table.concat(list, delim)
  614. end
  615. function core.is_nan(number)
  616. return number ~= number
  617. end
  618. --[[ Helper function for parsing an optionally relative number
  619. of a chat command parameter, using the chat command tilde notation.
  620. Parameters:
  621. * arg: String snippet containing the number; possible values:
  622. * "<number>": return as number
  623. * "~<number>": return relative_to + <number>
  624. * "~": return relative_to
  625. * Anything else will return `nil`
  626. * relative_to: Number to which the `arg` number might be relative to
  627. Returns:
  628. A number or `nil`, depending on `arg.
  629. Examples:
  630. * `core.parse_relative_number("5", 10)` returns 5
  631. * `core.parse_relative_number("~5", 10)` returns 15
  632. * `core.parse_relative_number("~", 10)` returns 10
  633. ]]
  634. function core.parse_relative_number(arg, relative_to)
  635. if not arg then
  636. return nil
  637. elseif arg == "~" then
  638. return relative_to
  639. elseif string.sub(arg, 1, 1) == "~" then
  640. local number = tonumber(string.sub(arg, 2))
  641. if not number then
  642. return nil
  643. end
  644. if core.is_nan(number) or number == math.huge or number == -math.huge then
  645. return nil
  646. end
  647. return relative_to + number
  648. else
  649. local number = tonumber(arg)
  650. if core.is_nan(number) or number == math.huge or number == -math.huge then
  651. return nil
  652. end
  653. return number
  654. end
  655. end
  656. --[[ Helper function to parse coordinates that might be relative
  657. to another position; supports chat command tilde notation.
  658. Intended to be used in chat command parameter parsing.
  659. Parameters:
  660. * x, y, z: Parsed x, y, and z coordinates as strings
  661. * relative_to: Position to which to compare the position
  662. Syntax of x, y and z:
  663. * "<number>": return as number
  664. * "~<number>": return <number> + player position on this axis
  665. * "~": return player position on this axis
  666. Returns: a vector or nil for invalid input or if player does not exist
  667. ]]
  668. function core.parse_coordinates(x, y, z, relative_to)
  669. if not relative_to then
  670. x, y, z = tonumber(x), tonumber(y), tonumber(z)
  671. return x and y and z and { x = x, y = y, z = z }
  672. end
  673. local rx = core.parse_relative_number(x, relative_to.x)
  674. local ry = core.parse_relative_number(y, relative_to.y)
  675. local rz = core.parse_relative_number(z, relative_to.z)
  676. return rx and ry and rz and { x = rx, y = ry, z = rz }
  677. end