misc_helpers.lua 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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. if delim == "" then
  164. error("string.split separator is empty", 2)
  165. end
  166. max_splits = max_splits or -2
  167. local items = {}
  168. local pos, len = 1, #str
  169. local plain = not sep_is_pattern
  170. max_splits = max_splits + 1
  171. repeat
  172. local np, npe = string_find(str, delim, pos, plain)
  173. np, npe = (np or (len+1)), (npe or (len+1))
  174. if (not np) or (max_splits == 1) then
  175. np = len + 1
  176. npe = np
  177. end
  178. local s = string_sub(str, pos, np - 1)
  179. if include_empty or (s ~= "") then
  180. max_splits = max_splits - 1
  181. items[#items + 1] = s
  182. end
  183. pos = npe + 1
  184. until (max_splits == 0) or (pos > (len + 1))
  185. return items
  186. end
  187. --------------------------------------------------------------------------------
  188. function table.indexof(list, val)
  189. for i, v in ipairs(list) do
  190. if v == val then
  191. return i
  192. end
  193. end
  194. return -1
  195. end
  196. --------------------------------------------------------------------------------
  197. function string:trim()
  198. return self:match("^%s*(.-)%s*$")
  199. end
  200. --------------------------------------------------------------------------------
  201. function math.hypot(x, y)
  202. return math.sqrt(x * x + y * y)
  203. end
  204. --------------------------------------------------------------------------------
  205. function math.sign(x, tolerance)
  206. tolerance = tolerance or 0
  207. if x > tolerance then
  208. return 1
  209. elseif x < -tolerance then
  210. return -1
  211. end
  212. return 0
  213. end
  214. --------------------------------------------------------------------------------
  215. function math.factorial(x)
  216. assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
  217. if x >= 171 then
  218. -- 171! is greater than the biggest double, no need to calculate
  219. return math.huge
  220. end
  221. local v = 1
  222. for k = 2, x do
  223. v = v * k
  224. end
  225. return v
  226. end
  227. function math.round(x)
  228. if x >= 0 then
  229. return math.floor(x + 0.5)
  230. end
  231. return math.ceil(x - 0.5)
  232. end
  233. local formspec_escapes = {
  234. ["\\"] = "\\\\",
  235. ["["] = "\\[",
  236. ["]"] = "\\]",
  237. [";"] = "\\;",
  238. [","] = "\\,",
  239. ["$"] = "\\$",
  240. }
  241. function core.formspec_escape(text)
  242. -- Use explicit character set instead of dot here because it doubles the performance
  243. return text and string.gsub(text, "[\\%[%];,$]", formspec_escapes)
  244. end
  245. function core.wrap_text(text, max_length, as_table)
  246. local result = {}
  247. local line = {}
  248. if #text <= max_length then
  249. return as_table and {text} or text
  250. end
  251. local line_length = 0
  252. for word in text:gmatch("%S+") do
  253. if line_length > 0 and line_length + #word + 1 >= max_length then
  254. -- word wouldn't fit on current line, move to next line
  255. table.insert(result, table.concat(line, " "))
  256. line = {word}
  257. line_length = #word
  258. else
  259. table.insert(line, word)
  260. line_length = line_length + 1 + #word
  261. end
  262. end
  263. table.insert(result, table.concat(line, " "))
  264. return as_table and result or table.concat(result, "\n")
  265. end
  266. --------------------------------------------------------------------------------
  267. if INIT == "game" then
  268. local dirs1 = {9, 18, 7, 12}
  269. local dirs2 = {20, 23, 22, 21}
  270. function core.rotate_and_place(itemstack, placer, pointed_thing,
  271. infinitestacks, orient_flags, prevent_after_place)
  272. orient_flags = orient_flags or {}
  273. local unode = core.get_node_or_nil(pointed_thing.under)
  274. if not unode then
  275. return
  276. end
  277. local undef = core.registered_nodes[unode.name]
  278. local sneaking = placer and placer:get_player_control().sneak
  279. if undef and undef.on_rightclick and not sneaking then
  280. return undef.on_rightclick(pointed_thing.under, unode, placer,
  281. itemstack, pointed_thing)
  282. end
  283. local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
  284. local above = pointed_thing.above
  285. local under = pointed_thing.under
  286. local iswall = (above.y == under.y)
  287. local isceiling = not iswall and (above.y < under.y)
  288. if undef and undef.buildable_to then
  289. iswall = false
  290. end
  291. if orient_flags.force_floor then
  292. iswall = false
  293. isceiling = false
  294. elseif orient_flags.force_ceiling then
  295. iswall = false
  296. isceiling = true
  297. elseif orient_flags.force_wall then
  298. iswall = true
  299. isceiling = false
  300. elseif orient_flags.invert_wall then
  301. iswall = not iswall
  302. end
  303. local param2 = fdir
  304. if iswall then
  305. param2 = dirs1[fdir + 1]
  306. elseif isceiling then
  307. if orient_flags.force_facedir then
  308. param2 = 20
  309. else
  310. param2 = dirs2[fdir + 1]
  311. end
  312. else -- place right side up
  313. if orient_flags.force_facedir then
  314. param2 = 0
  315. end
  316. end
  317. local old_itemstack = ItemStack(itemstack)
  318. local new_itemstack = core.item_place_node(itemstack, placer,
  319. pointed_thing, param2, prevent_after_place)
  320. return infinitestacks and old_itemstack or new_itemstack
  321. end
  322. --------------------------------------------------------------------------------
  323. --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
  324. --implies infinite stacks when performing a 6d rotation.
  325. --------------------------------------------------------------------------------
  326. core.rotate_node = function(itemstack, placer, pointed_thing)
  327. local name = placer and placer:get_player_name() or ""
  328. local invert_wall = placer and placer:get_player_control().sneak or false
  329. return core.rotate_and_place(itemstack, placer, pointed_thing,
  330. core.is_creative_enabled(name),
  331. {invert_wall = invert_wall}, true)
  332. end
  333. end
  334. --------------------------------------------------------------------------------
  335. function core.explode_table_event(evt)
  336. if evt ~= nil then
  337. local parts = evt:split(":")
  338. if #parts == 3 then
  339. local t = parts[1]:trim()
  340. local r = tonumber(parts[2]:trim())
  341. local c = tonumber(parts[3]:trim())
  342. if type(r) == "number" and type(c) == "number"
  343. and t ~= "INV" then
  344. return {type=t, row=r, column=c}
  345. end
  346. end
  347. end
  348. return {type="INV", row=0, column=0}
  349. end
  350. --------------------------------------------------------------------------------
  351. function core.explode_textlist_event(evt)
  352. if evt ~= nil then
  353. local parts = evt:split(":")
  354. if #parts == 2 then
  355. local t = parts[1]:trim()
  356. local r = tonumber(parts[2]:trim())
  357. if type(r) == "number" and t ~= "INV" then
  358. return {type=t, index=r}
  359. end
  360. end
  361. end
  362. return {type="INV", index=0}
  363. end
  364. --------------------------------------------------------------------------------
  365. function core.explode_scrollbar_event(evt)
  366. local retval = core.explode_textlist_event(evt)
  367. retval.value = retval.index
  368. retval.index = nil
  369. return retval
  370. end
  371. --------------------------------------------------------------------------------
  372. function core.rgba(r, g, b, a)
  373. return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
  374. string.format("#%02X%02X%02X", r, g, b)
  375. end
  376. --------------------------------------------------------------------------------
  377. function core.pos_to_string(pos, decimal_places)
  378. local x = pos.x
  379. local y = pos.y
  380. local z = pos.z
  381. if decimal_places ~= nil then
  382. x = string.format("%." .. decimal_places .. "f", x)
  383. y = string.format("%." .. decimal_places .. "f", y)
  384. z = string.format("%." .. decimal_places .. "f", z)
  385. end
  386. return "(" .. x .. "," .. y .. "," .. z .. ")"
  387. end
  388. --------------------------------------------------------------------------------
  389. function core.string_to_pos(value)
  390. if value == nil then
  391. return nil
  392. end
  393. value = value:match("^%((.-)%)$") or value -- strip parentheses
  394. local x, y, z = value:trim():match("^([%d.-]+)[,%s]%s*([%d.-]+)[,%s]%s*([%d.-]+)$")
  395. if x and y and z then
  396. x = tonumber(x)
  397. y = tonumber(y)
  398. z = tonumber(z)
  399. return vector.new(x, y, z)
  400. end
  401. return nil
  402. end
  403. --------------------------------------------------------------------------------
  404. do
  405. local rel_num_cap = "(~?-?%d*%.?%d*)" -- may be overly permissive as this will be tonumber'ed anyways
  406. local num_delim = "[,%s]%s*"
  407. local pattern = "^" .. table.concat({rel_num_cap, rel_num_cap, rel_num_cap}, num_delim) .. "$"
  408. local function parse_area_string(pos, relative_to)
  409. local pp = {}
  410. pp.x, pp.y, pp.z = pos:trim():match(pattern)
  411. return core.parse_coordinates(pp.x, pp.y, pp.z, relative_to)
  412. end
  413. function core.string_to_area(value, relative_to)
  414. local p1, p2 = value:match("^%((.-)%)%s*%((.-)%)$")
  415. if not p1 then
  416. return
  417. end
  418. p1 = parse_area_string(p1, relative_to)
  419. p2 = parse_area_string(p2, relative_to)
  420. if p1 == nil or p2 == nil then
  421. return
  422. end
  423. return p1, p2
  424. end
  425. end
  426. --------------------------------------------------------------------------------
  427. function table.copy(t, seen)
  428. local n = {}
  429. seen = seen or {}
  430. seen[t] = n
  431. for k, v in pairs(t) do
  432. n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
  433. (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
  434. end
  435. return n
  436. end
  437. function table.insert_all(t, other)
  438. for i=1, #other do
  439. t[#t + 1] = other[i]
  440. end
  441. return t
  442. end
  443. function table.key_value_swap(t)
  444. local ti = {}
  445. for k,v in pairs(t) do
  446. ti[v] = k
  447. end
  448. return ti
  449. end
  450. function table.shuffle(t, from, to, random)
  451. from = from or 1
  452. to = to or #t
  453. random = random or math.random
  454. local n = to - from + 1
  455. while n > 1 do
  456. local r = from + n-1
  457. local l = from + random(0, n-1)
  458. t[l], t[r] = t[r], t[l]
  459. n = n-1
  460. end
  461. end
  462. --------------------------------------------------------------------------------
  463. -- mainmenu only functions
  464. --------------------------------------------------------------------------------
  465. if core.gettext then -- for client and mainmenu
  466. function fgettext_ne(text, ...)
  467. text = core.gettext(text)
  468. local arg = {n=select('#', ...), ...}
  469. if arg.n >= 1 then
  470. -- Insert positional parameters ($1, $2, ...)
  471. local result = ''
  472. local pos = 1
  473. while pos <= text:len() do
  474. local newpos = text:find('[$]', pos)
  475. if newpos == nil then
  476. result = result .. text:sub(pos)
  477. pos = text:len() + 1
  478. else
  479. local paramindex =
  480. tonumber(text:sub(newpos+1, newpos+1))
  481. result = result .. text:sub(pos, newpos-1)
  482. .. tostring(arg[paramindex])
  483. pos = newpos + 2
  484. end
  485. end
  486. text = result
  487. end
  488. return text
  489. end
  490. function fgettext(text, ...)
  491. return core.formspec_escape(fgettext_ne(text, ...))
  492. end
  493. end
  494. local ESCAPE_CHAR = string.char(0x1b)
  495. function core.get_color_escape_sequence(color)
  496. return ESCAPE_CHAR .. "(c@" .. color .. ")"
  497. end
  498. function core.get_background_escape_sequence(color)
  499. return ESCAPE_CHAR .. "(b@" .. color .. ")"
  500. end
  501. function core.colorize(color, message)
  502. local lines = tostring(message):split("\n", true)
  503. local color_code = core.get_color_escape_sequence(color)
  504. for i, line in ipairs(lines) do
  505. lines[i] = color_code .. line
  506. end
  507. return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
  508. end
  509. function core.strip_foreground_colors(str)
  510. return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
  511. end
  512. function core.strip_background_colors(str)
  513. return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
  514. end
  515. function core.strip_colors(str)
  516. return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
  517. end
  518. function core.translate(textdomain, str, ...)
  519. local start_seq
  520. if textdomain == "" then
  521. start_seq = ESCAPE_CHAR .. "T"
  522. else
  523. start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
  524. end
  525. local arg = {n=select('#', ...), ...}
  526. local end_seq = ESCAPE_CHAR .. "E"
  527. local arg_index = 1
  528. local translated = str:gsub("@(.)", function(matched)
  529. local c = string.byte(matched)
  530. if string.byte("1") <= c and c <= string.byte("9") then
  531. local a = c - string.byte("0")
  532. if a ~= arg_index then
  533. error("Escape sequences in string given to core.translate " ..
  534. "are not in the correct order: got @" .. matched ..
  535. "but expected @" .. tostring(arg_index))
  536. end
  537. if a > arg.n then
  538. error("Not enough arguments provided to core.translate")
  539. end
  540. arg_index = arg_index + 1
  541. return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
  542. elseif matched == "n" then
  543. return "\n"
  544. else
  545. return matched
  546. end
  547. end)
  548. if arg_index < arg.n + 1 then
  549. error("Too many arguments provided to core.translate")
  550. end
  551. return start_seq .. translated .. end_seq
  552. end
  553. function core.get_translator(textdomain)
  554. return function(str, ...) return core.translate(textdomain or "", str, ...) end
  555. end
  556. --------------------------------------------------------------------------------
  557. -- Returns the exact coordinate of a pointed surface
  558. --------------------------------------------------------------------------------
  559. function core.pointed_thing_to_face_pos(placer, pointed_thing)
  560. -- Avoid crash in some situations when player is inside a node, causing
  561. -- 'above' to equal 'under'.
  562. if vector.equals(pointed_thing.above, pointed_thing.under) then
  563. return pointed_thing.under
  564. end
  565. local eye_height = placer:get_properties().eye_height
  566. local eye_offset_first = placer:get_eye_offset()
  567. local node_pos = pointed_thing.under
  568. local camera_pos = placer:get_pos()
  569. local pos_off = vector.multiply(
  570. vector.subtract(pointed_thing.above, node_pos), 0.5)
  571. local look_dir = placer:get_look_dir()
  572. local offset, nc
  573. local oc = {}
  574. for c, v in pairs(pos_off) do
  575. if nc or v == 0 then
  576. oc[#oc + 1] = c
  577. else
  578. offset = v
  579. nc = c
  580. end
  581. end
  582. local fine_pos = {[nc] = node_pos[nc] + offset}
  583. camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
  584. local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
  585. for i = 1, #oc do
  586. fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
  587. end
  588. return fine_pos
  589. end
  590. function core.string_to_privs(str, delim)
  591. assert(type(str) == "string")
  592. delim = delim or ','
  593. local privs = {}
  594. for _, priv in pairs(string.split(str, delim)) do
  595. privs[priv:trim()] = true
  596. end
  597. return privs
  598. end
  599. function core.privs_to_string(privs, delim)
  600. assert(type(privs) == "table")
  601. delim = delim or ','
  602. local list = {}
  603. for priv, bool in pairs(privs) do
  604. if bool then
  605. list[#list + 1] = priv
  606. end
  607. end
  608. return table.concat(list, delim)
  609. end
  610. function core.is_nan(number)
  611. return number ~= number
  612. end
  613. --[[ Helper function for parsing an optionally relative number
  614. of a chat command parameter, using the chat command tilde notation.
  615. Parameters:
  616. * arg: String snippet containing the number; possible values:
  617. * "<number>": return as number
  618. * "~<number>": return relative_to + <number>
  619. * "~": return relative_to
  620. * Anything else will return `nil`
  621. * relative_to: Number to which the `arg` number might be relative to
  622. Returns:
  623. A number or `nil`, depending on `arg.
  624. Examples:
  625. * `core.parse_relative_number("5", 10)` returns 5
  626. * `core.parse_relative_number("~5", 10)` returns 15
  627. * `core.parse_relative_number("~", 10)` returns 10
  628. ]]
  629. function core.parse_relative_number(arg, relative_to)
  630. if not arg then
  631. return nil
  632. elseif arg == "~" then
  633. return relative_to
  634. elseif string.sub(arg, 1, 1) == "~" then
  635. local number = tonumber(string.sub(arg, 2))
  636. if not number then
  637. return nil
  638. end
  639. if core.is_nan(number) or number == math.huge or number == -math.huge then
  640. return nil
  641. end
  642. return relative_to + number
  643. else
  644. local number = tonumber(arg)
  645. if core.is_nan(number) or number == math.huge or number == -math.huge then
  646. return nil
  647. end
  648. return number
  649. end
  650. end
  651. --[[ Helper function to parse coordinates that might be relative
  652. to another position; supports chat command tilde notation.
  653. Intended to be used in chat command parameter parsing.
  654. Parameters:
  655. * x, y, z: Parsed x, y, and z coordinates as strings
  656. * relative_to: Position to which to compare the position
  657. Syntax of x, y and z:
  658. * "<number>": return as number
  659. * "~<number>": return <number> + player position on this axis
  660. * "~": return player position on this axis
  661. Returns: a vector or nil for invalid input or if player does not exist
  662. ]]
  663. function core.parse_coordinates(x, y, z, relative_to)
  664. if not relative_to then
  665. x, y, z = tonumber(x), tonumber(y), tonumber(z)
  666. return x and y and z and { x = x, y = y, z = z }
  667. end
  668. local rx = core.parse_relative_number(x, relative_to.x)
  669. local ry = core.parse_relative_number(y, relative_to.y)
  670. local rz = core.parse_relative_number(z, relative_to.z)
  671. return rx and ry and rz and { x = rx, y = ry, z = rz }
  672. end