misc_helpers.lua 21 KB

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