· 5 years ago · Oct 18, 2020, 11:04 PM
1--- The @{textutils} API provides helpful utilities for formatting and
2-- manipulating strings.
3--
4-- @module textutils
5
6local expect = dofile("rom/modules/main/cc/expect.lua")
7local expect, field = expect.expect, expect.field
8
9--- Slowly writes string text at current cursor position,
10-- character-by-character.
11--
12-- Like @{write}, this does not insert a newline at the end.
13--
14-- @tparam string sText The the text to write to the screen
15-- @tparam[opt] number nRate The number of characters to write each second,
16-- Defaults to 20.
17-- @usage textutils.slowWrite("Hello, world!")
18-- @usage textutils.slowWrite("Hello, world!", 5)
19function slowWrite(sText, nRate)
20 expect(2, nRate, "number", "nil")
21 nRate = nRate or 20
22 if nRate < 0 then
23 error("Rate must be positive", 2)
24 end
25 local nSleep = 1 / nRate
26
27 sText = tostring(sText)
28 local x, y = term.getCursorPos()
29 local len = #sText
30
31 for n = 1, len do
32 term.setCursorPos(x, y)
33 sleep(nSleep)
34 local nLines = write(string.sub(sText, 1, n))
35 local _, newY = term.getCursorPos()
36 y = newY - nLines
37 end
38end
39
40--- Slowly prints string text at current cursor position,
41-- character-by-character.
42--
43-- Like @{print}, this inserts a newline after printing.
44--
45-- @tparam string sText The the text to write to the screen
46-- @tparam[opt] number nRate The number of characters to write each second,
47-- Defaults to 20.
48-- @usage textutils.slowPrint("Hello, world!")
49-- @usage textutils.slowPrint("Hello, world!", 5)
50function slowPrint(sText, nRate)
51 slowWrite(sText, nRate)
52 print()
53end
54
55--- Takes input time and formats it in a more readable format such as `6:30 PM`.
56--
57-- @tparam number nTime The time to format, as provided by @{os.time}.
58-- @tparam[opt] boolean bTwentyFourHour Whether to format this as a 24-hour
59-- clock (`18:30`) rather than a 12-hour one (`6:30 AM`)
60-- @treturn string The formatted time
61-- @usage textutils.formatTime(os.time())
62function formatTime(nTime, bTwentyFourHour)
63 expect(1, nTime, "number")
64 expect(2, bTwentyFourHour, "boolean", "nil")
65 local sTOD = nil
66 if not bTwentyFourHour then
67 if nTime >= 12 then
68 sTOD = "PM"
69 else
70 sTOD = "AM"
71 end
72 if nTime >= 13 then
73 nTime = nTime - 12
74 end
75 end
76
77 local nHour = math.floor(nTime)
78 local nMinute = math.floor((nTime - nHour) * 60)
79 if sTOD then
80 return string.format("%d:%02d %s", nHour == 0 and 12 or nHour, nMinute, sTOD)
81 else
82 return string.format("%d:%02d", nHour, nMinute)
83 end
84end
85
86local function makePagedScroll(_term, _nFreeLines)
87 local nativeScroll = _term.scroll
88 local nFreeLines = _nFreeLines or 0
89 return function(_n)
90 for _ = 1, _n do
91 nativeScroll(1)
92
93 if nFreeLines <= 0 then
94 local _, h = _term.getSize()
95 _term.setCursorPos(1, h)
96 _term.write("Press any key to continue")
97 os.pullEvent("key")
98 _term.clearLine()
99 _term.setCursorPos(1, h)
100 else
101 nFreeLines = nFreeLines - 1
102 end
103 end
104 end
105end
106
107--- Prints a given string to the display.
108--
109-- If the action can be completed without scrolling, it acts much the same as
110-- @{print}; otherwise, it will throw up a "Press any key to continue" prompt at
111-- the bottom of the display. Each press will cause it to scroll down and write
112-- a single line more before prompting again, if need be.
113--
114-- @tparam string _sText The text to print to the screen.
115-- @tparam[opt] number _nFreeLines The number of lines which will be
116-- automatically scrolled before the first prompt appears (meaning _nFreeLines +
117-- 1 lines will be printed). This can be set to the terminal's height - 2 to
118-- always try to fill the screen. Defaults to 0, meaning only one line is
119-- displayed before prompting.
120-- @treturn number The number of lines printed.
121-- @usage
122-- local width, height = term.getSize()
123-- textutils.pagedPrint(("This is a rather verbose dose of repetition.\n"):rep(30), height - 2)
124function pagedPrint(_sText, _nFreeLines)
125 expect(2, _nFreeLines, "number", "nil")
126 -- Setup a redirector
127 local oldTerm = term.current()
128 local newTerm = {}
129 for k, v in pairs(oldTerm) do
130 newTerm[k] = v
131 end
132 newTerm.scroll = makePagedScroll(oldTerm, _nFreeLines)
133 term.redirect(newTerm)
134
135 -- Print the text
136 local result
137 local ok, err = pcall(function()
138 if _sText ~= nil then
139 result = print(_sText)
140 else
141 result = print()
142 end
143 end)
144
145 -- Removed the redirector
146 term.redirect(oldTerm)
147
148 -- Propogate errors
149 if not ok then
150 error(err, 0)
151 end
152 return result
153end
154
155local function tabulateCommon(bPaged, ...)
156 local tAll = table.pack(...)
157 for i = 1, tAll.n do
158 expect(i, tAll[i], "number", "table")
159 end
160
161 local w, h = term.getSize()
162 local nMaxLen = w / 8
163 for n, t in ipairs(tAll) do
164 if type(t) == "table" then
165 for nu, sItem in pairs(t) do
166 if type(sItem) ~= "string" then
167 error("bad argument #" .. n .. "." .. nu .. " (expected string, got " .. type(sItem) .. ")", 3)
168 end
169 nMaxLen = math.max(#sItem + 1, nMaxLen)
170 end
171 end
172 end
173 local nCols = math.floor(w / nMaxLen)
174 local nLines = 0
175 local function newLine()
176 if bPaged and nLines >= h - 3 then
177 pagedPrint()
178 else
179 print()
180 end
181 nLines = nLines + 1
182 end
183
184 local function drawCols(_t)
185 local nCol = 1
186 for _, s in ipairs(_t) do
187 if nCol > nCols then
188 nCol = 1
189 newLine()
190 end
191
192 local cx, cy = term.getCursorPos()
193 cx = 1 + (nCol - 1) * nMaxLen
194 term.setCursorPos(cx, cy)
195 term.write(s)
196
197 nCol = nCol + 1
198 end
199 print()
200 end
201 for _, t in ipairs(tAll) do
202 if type(t) == "table" then
203 if #t > 0 then
204 drawCols(t)
205 end
206 elseif type(t) == "number" then
207 term.setTextColor(t)
208 end
209 end
210end
211
212--- Prints tables in a structured form.
213--
214-- This accepts multiple arguments, either a table or a number. When
215-- encountering a table, this will be treated as a table row, with each column
216-- width being auto-adjusted.
217--
218-- When encountering a number, this sets the text color of the subsequent rows to it.
219--
220-- @tparam {string...}|number ... The rows and text colors to display.
221-- @usage textutils.tabulate(colors.orange, { "1", "2", "3" }, colors.lightBlue, { "A", "B", "C" })
222function tabulate(...)
223 return tabulateCommon(false, ...)
224end
225
226--- Prints tables in a structured form, stopping and prompting for input should
227-- the result not fit on the terminal.
228--
229-- This functions identically to @{textutils.tabulate}, but will prompt for user
230-- input should the whole output not fit on the display.
231--
232-- @tparam {string...}|number ... The rows and text colors to display.
233-- @usage textutils.tabulate(colors.orange, { "1", "2", "3" }, colors.lightBlue, { "A", "B", "C" })
234-- @see textutils.tabulate
235-- @see textutils.pagedPrint
236function pagedTabulate(...)
237 return tabulateCommon(true, ...)
238end
239
240local g_tLuaKeywords = {
241 ["and"] = true,
242 ["break"] = true,
243 ["do"] = true,
244 ["else"] = true,
245 ["elseif"] = true,
246 ["end"] = true,
247 ["false"] = true,
248 ["for"] = true,
249 ["function"] = true,
250 ["if"] = true,
251 ["in"] = true,
252 ["local"] = true,
253 ["nil"] = true,
254 ["not"] = true,
255 ["or"] = true,
256 ["repeat"] = true,
257 ["return"] = true,
258 ["then"] = true,
259 ["true"] = true,
260 ["until"] = true,
261 ["while"] = true,
262}
263
264local function serializeImpl(t, tTracking, sIndent)
265 local sType = type(t)
266 if sType == "table" then
267 if tTracking[t] ~= nil then
268 error("Cannot serialize table with recursive entries", 0)
269 end
270 tTracking[t] = true
271
272 if next(t) == nil then
273 -- Empty tables are simple
274 return "{}"
275 else
276 -- Other tables take more work
277 local sResult = "{\n"
278 local sSubIndent = sIndent .. " "
279 local tSeen = {}
280 for k, v in ipairs(t) do
281 tSeen[k] = true
282 sResult = sResult .. sSubIndent .. serializeImpl(v, tTracking, sSubIndent) .. ",\n"
283 end
284 for k, v in pairs(t) do
285 if not tSeen[k] then
286 local sEntry
287 if type(k) == "string" and not g_tLuaKeywords[k] and string.match(k, "^[%a_][%a%d_]*$") then
288 sEntry = k .. " = " .. serializeImpl(v, tTracking, sSubIndent) .. ",\n"
289 else
290 sEntry = "[ " .. serializeImpl(k, tTracking, sSubIndent) .. " ] = " .. serializeImpl(v, tTracking, sSubIndent) .. ",\n"
291 end
292 sResult = sResult .. sSubIndent .. sEntry
293 end
294 end
295 sResult = sResult .. sIndent .. "}"
296 return sResult
297 end
298
299 elseif sType == "string" then
300 return string.format("%q", t)
301
302 elseif sType == "number" or sType == "boolean" or sType == "nil" then
303 return tostring(t)
304
305 else
306 error("Cannot serialize type " .. sType, 0)
307
308 end
309end
310
311local function mk_tbl(str, name)
312 local msg = "attempt to mutate textutils." .. name
313 return setmetatable({}, {
314 __newindex = function() error(msg, 2) end,
315 __tostring = function() return str end,
316 })
317end
318
319--- A table representing an empty JSON array, in order to distinguish it from an
320-- empty JSON object.
321--
322-- The contents of this table should not be modified.
323--
324-- @usage textutils.serialiseJSON(textutils.empty_json_array)
325-- @see textutils.serialiseJSON
326-- @see textutils.unserialiseJSON
327empty_json_array = mk_tbl("[]", "empty_json_array")
328
329--- A table representing the JSON null value.
330--
331-- The contents of this table should not be modified.
332--
333-- @usage textutils.serialiseJSON(textutils.json_null)
334-- @see textutils.serialiseJSON
335-- @see textutils.unserialiseJSON
336json_null = mk_tbl("null", "json_null")
337
338local serializeJSONString
339do
340 local function hexify(c)
341 return ("\\u00%02X"):format(c:byte())
342 end
343
344 local map = {
345 ["\""] = "\\\"",
346 ["\\"] = "\\\\",
347 ["\b"] = "\\b",
348 ["\f"] = "\\f",
349 ["\n"] = "\\n",
350 ["\r"] = "\\r",
351 ["\t"] = "\\t",
352 }
353 for i = 0, 0x1f do
354 local c = string.char(i)
355 if map[c] == nil then map[c] = hexify(c) end
356 end
357
358 serializeJSONString = function(s)
359 return ('"%s"'):format(s:gsub("[\0-\x1f\"\\]", map):gsub("[\x7f-\xff]", hexify))
360 end
361end
362
363local function serializeJSONImpl(t, tTracking, bNBTStyle)
364 local sType = type(t)
365 if t == empty_json_array then return "[]"
366 elseif t == json_null then return "null"
367
368 elseif sType == "table" then
369 if tTracking[t] ~= nil then
370 error("Cannot serialize table with recursive entries", 0)
371 end
372 tTracking[t] = true
373
374 if next(t) == nil then
375 -- Empty tables are simple
376 return "{}"
377 else
378 -- Other tables take more work
379 local sObjectResult = "{"
380 local sArrayResult = "["
381 local nObjectSize = 0
382 local nArraySize = 0
383 for k, v in pairs(t) do
384 if type(k) == "string" then
385 local sEntry
386 if bNBTStyle then
387 sEntry = tostring(k) .. ":" .. serializeJSONImpl(v, tTracking, bNBTStyle)
388 else
389 sEntry = serializeJSONString(k) .. ":" .. serializeJSONImpl(v, tTracking, bNBTStyle)
390 end
391 if nObjectSize == 0 then
392 sObjectResult = sObjectResult .. sEntry
393 else
394 sObjectResult = sObjectResult .. "," .. sEntry
395 end
396 nObjectSize = nObjectSize + 1
397 end
398 end
399 for _, v in ipairs(t) do
400 local sEntry = serializeJSONImpl(v, tTracking, bNBTStyle)
401 if nArraySize == 0 then
402 sArrayResult = sArrayResult .. sEntry
403 else
404 sArrayResult = sArrayResult .. "," .. sEntry
405 end
406 nArraySize = nArraySize + 1
407 end
408 sObjectResult = sObjectResult .. "}"
409 sArrayResult = sArrayResult .. "]"
410 if nObjectSize > 0 or nArraySize == 0 then
411 return sObjectResult
412 else
413 return sArrayResult
414 end
415 end
416
417 elseif sType == "string" then
418 return serializeJSONString(t)
419
420 elseif sType == "number" or sType == "boolean" then
421 return tostring(t)
422
423 else
424 error("Cannot serialize type " .. sType, 0)
425
426 end
427end
428
429local unserialise_json
430do
431 local sub, find, match, concat, tonumber = string.sub, string.find, string.match, table.concat, tonumber
432
433 --- Skip any whitespace
434 local function skip(str, pos)
435 local _, last = find(str, "^[ \n\r\t]+", pos)
436 if last then return last + 1 else return pos end
437 end
438
439 local escapes = {
440 ["b"] = '\b', ["f"] = '\f', ["n"] = '\n', ["r"] = '\r', ["t"] = '\t',
441 ["\""] = "\"", ["/"] = "/", ["\\"] = "\\",
442 }
443
444 local mt = {}
445
446 local function error_at(pos, msg, ...)
447 if select('#', ...) > 0 then msg = msg:format(...) end
448 error(setmetatable({ pos = pos, msg = msg }, mt))
449 end
450
451 local function expected(pos, actual, exp)
452 if actual == "" then actual = "end of input" else actual = ("%q"):format(actual) end
453 error_at(pos, "Unexpected %s, expected %s.", actual, exp)
454 end
455
456 local function parse_string(str, pos)
457 local buf, n = {}, 1
458
459 while true do
460 local c = sub(str, pos, pos)
461 if c == "" then error_at(pos, "Unexpected end of input, expected '\"'.") end
462 if c == '"' then break end
463
464 if c == '\\' then
465 -- Handle the various escapes
466 c = sub(str, pos + 1, pos + 1)
467 if c == "" then error_at(pos, "Unexpected end of input, expected escape sequence.") end
468
469 if c == "u" then
470 local num_str = match(str, "^%x%x%x%x", pos + 2)
471 if not num_str then error_at(pos, "Malformed unicode escape %q.", sub(str, pos + 2, pos + 5)) end
472 buf[n], n, pos = utf8.char(tonumber(num_str, 16)), n + 1, pos + 6
473 else
474 local unesc = escapes[c]
475 if not unesc then error_at(pos + 1, "Unknown escape character %q.", c) end
476 buf[n], n, pos = unesc, n + 1, pos + 2
477 end
478 elseif c >= '\x20' then
479 buf[n], n, pos = c, n + 1, pos + 1
480 else
481 error_at(pos + 1, "Unescaped whitespace %q.", c)
482 end
483 end
484
485 return concat(buf, "", 1, n - 1), pos + 1
486 end
487
488 local valid = { b = true, B = true, s = true, S = true, l = true, L = true, f = true, F = true, d = true, D = true }
489 local function parse_number(str, pos, opts)
490 local _, last, num_str = find(str, '^(-?%d+%.?%d*[eE]?[+-]?%d*)', pos)
491 local val = tonumber(num_str)
492 if not val then error_at(pos, "Malformed number %q.", num_str) end
493
494 if opts.nbt_style and valid[sub(str, last + 1, last + 1)] then return val, last + 2 end
495
496 return val, last + 1
497 end
498
499 local function parse_ident(str, pos)
500 local _, last, val = find(str, '^([%a][%w_]*)', pos)
501 return val, last + 1
502 end
503
504 local function decode_impl(str, pos, opts)
505 local c = sub(str, pos, pos)
506 if c == '"' then return parse_string(str, pos + 1)
507 elseif c == "-" or c >= "0" and c <= "9" then return parse_number(str, pos, opts)
508 elseif c == "t" then
509 if sub(str, pos + 1, pos + 3) == "rue" then return true, pos + 4 end
510 elseif c == 'f' then
511 if sub(str, pos + 1, pos + 4) == "alse" then return false, pos + 5 end
512 elseif c == 'n' then
513 if sub(str, pos + 1, pos + 3) == "ull" then
514 if opts.parse_null then
515 return json_null, pos + 4
516 else
517 return nil, pos + 4
518 end
519 end
520 elseif c == "{" then
521 local obj = {}
522
523 pos = skip(str, pos + 1)
524 c = sub(str, pos, pos)
525
526 if c == "" then return error_at(pos, "Unexpected end of input, expected '}'.") end
527 if c == "}" then return obj, pos + 1 end
528
529 while true do
530 local key, value
531 if c == "\"" then key, pos = parse_string(str, pos + 1)
532 elseif opts.nbt_style then key, pos = parse_ident(str, pos)
533 else return expected(pos, c, "object key")
534 end
535
536 pos = skip(str, pos)
537
538 c = sub(str, pos, pos)
539 if c ~= ":" then return expected(pos, c, "':'") end
540
541 value, pos = decode_impl(str, skip(str, pos + 1), opts)
542 obj[key] = value
543
544 -- Consume the next delimiter
545 pos = skip(str, pos)
546 c = sub(str, pos, pos)
547 if c == "}" then break
548 elseif c == "," then pos = skip(str, pos + 1)
549 else return expected(pos, c, "',' or '}'")
550 end
551
552 c = sub(str, pos, pos)
553 end
554
555 return obj, pos + 1
556
557 elseif c == "[" then
558 local arr, n = {}, 1
559
560 pos = skip(str, pos + 1)
561 c = sub(str, pos, pos)
562
563 if c == "" then return expected(pos, c, "']'") end
564 if c == "]" then return empty_json_array, pos + 1 end
565
566 while true do
567 n, arr[n], pos = n + 1, decode_impl(str, pos, opts)
568
569 -- Consume the next delimiter
570 pos = skip(str, pos)
571 c = sub(str, pos, pos)
572 if c == "]" then break
573 elseif c == "," then pos = skip(str, pos + 1)
574 else return expected(pos, c, "',' or ']'")
575 end
576 end
577
578 return arr, pos + 1
579 elseif c == "" then error_at(pos, 'Unexpected end of input.')
580 end
581
582 error_at(pos, "Unexpected character %q.", c)
583 end
584
585 --- Converts a serialised JSON string back into a reassembled Lua object.
586 --
587 -- This may be used with @{textutils.serializeJSON}, or when communicating
588 -- with command blocks or web APIs.
589 --
590 -- @tparam string s The serialised string to deserialise.
591 -- @tparam[opt] { nbt_style? = boolean, parse_null? = boolean } options
592 -- Options which control how this JSON object is parsed.
593 --
594 -- - `nbt_style`: When true, this will accept [stringified NBT][nbt] strings,
595 -- as produced by many commands.
596 -- - `parse_null`: When true, `null` will be parsed as @{json_null}, rather
597 -- than `nil`.
598 --
599 -- [nbt]: https://minecraft.gamepedia.com/NBT_format
600 -- @return[1] The deserialised object
601 -- @treturn[2] nil If the object could not be deserialised.
602 -- @treturn string A message describing why the JSON string is invalid.
603 unserialise_json = function(s, options)
604 expect(1, s, "string")
605 expect(2, options, "table", "nil")
606
607 if options then
608 field(options, "nbt_style", "boolean", "nil")
609 field(options, "nbt_style", "boolean", "nil")
610 else
611 options = {}
612 end
613
614 local ok, res, pos = pcall(decode_impl, s, skip(s, 1), options)
615 if not ok then
616 if type(res) == "table" and getmetatable(res) == mt then
617 return nil, ("Malformed JSON at position %d: %s"):format(res.pos, res.msg)
618 end
619
620 error(res, 0)
621 end
622
623 pos = skip(s, pos)
624 if pos <= #s then
625 return nil, ("Malformed JSON at position %d: Unexpected trailing character %q."):format(pos, sub(s, pos, pos))
626 end
627 return res
628
629 end
630end
631
632--- Convert a Lua object into a textual representation, suitable for
633-- saving in a file or pretty-printing.
634--
635-- @param t The object to serialise
636-- @treturn string The serialised representation
637-- @throws If the object contains a value which cannot be
638-- serialised. This includes functions and tables which appear multiple
639-- times.
640function serialize(t)
641 local tTracking = {}
642 return serializeImpl(t, tTracking, "")
643end
644
645serialise = serialize -- GB version
646
647--- Converts a serialised string back into a reassembled Lua object.
648--
649-- This is mainly used together with @{textutils.serialize}.
650--
651-- @tparam string s The serialised string to deserialise.
652-- @return[1] The deserialised object
653-- @treturn[2] nil If the object could not be deserialised.
654function unserialize(s)
655 expect(1, s, "string")
656 local func = load("return " .. s, "unserialize", "t", {})
657 if func then
658 local ok, result = pcall(func)
659 if ok then
660 return result
661 end
662 end
663 return nil
664end
665
666unserialise = unserialize -- GB version
667
668--- Returns a JSON representation of the given data.
669--
670-- This function attempts to guess whether a table is a JSON array or
671-- object. However, empty tables are assumed to be empty objects - use
672-- @{textutils.empty_json_array} to mark an empty array.
673--
674-- This is largely intended for interacting with various functions from the
675-- @{commands} API, though may also be used in making @{http} requests.
676--
677-- @param t The value to serialise. Like @{textutils.serialise}, this should not
678-- contain recursive tables or functions.
679-- @tparam[opt] boolean bNBTStyle Whether to produce NBT-style JSON (non-quoted keys)
680-- instead of standard JSON.
681-- @treturn string The JSON representation of the input.
682-- @throws If the object contains a value which cannot be
683-- serialised. This includes functions and tables which appear multiple
684-- times.
685-- @usage textutils.serializeJSON({ values = { 1, "2", true } })
686function serializeJSON(t, bNBTStyle)
687 expect(1, t, "table", "string", "number", "boolean")
688 expect(2, bNBTStyle, "boolean", "nil")
689 local tTracking = {}
690 return serializeJSONImpl(t, tTracking, bNBTStyle or false)
691end
692
693serialiseJSON = serializeJSON -- GB version
694
695unserializeJSON = unserialise_json
696unserialiseJSON = unserialise_json
697
698--- Replaces certain characters in a string to make it safe for use in URLs or POST data.
699--
700-- @tparam string str The string to encode
701-- @treturn string The encoded string.
702-- @usage print("https://example.com/?view=" .. textutils.urlEncode(read()))
703function urlEncode(str)
704 expect(1, str, "string")
705 if str then
706 str = string.gsub(str, "\n", "\r\n")
707 str = string.gsub(str, "([^A-Za-z0-9 %-%_%.])", function(c)
708 local n = string.byte(c)
709 if n < 128 then
710 -- ASCII
711 return string.format("%%%02X", n)
712 else
713 -- Non-ASCII (encode as UTF-8)
714 return
715 string.format("%%%02X", 192 + bit32.band(bit32.arshift(n, 6), 31)) ..
716 string.format("%%%02X", 128 + bit32.band(n, 63))
717 end
718 end)
719 str = string.gsub(str, " ", "+")
720 end
721 return str
722end
723
724local tEmpty = {}
725
726--- Provides a list of possible completions for a partial Lua expression.
727--
728-- If the completed element is a table, suggestions will have `.` appended to
729-- them. Similarly, functions have `(` appended to them.
730--
731-- @tparam string sSearchText The partial expression to complete, such as a
732-- variable name or table index.
733--
734-- @tparam[opt] table tSearchTable The table to find variables in, defaulting to
735-- the global environment (@{_G}). The function also searches the "parent"
736-- environment via the `__index` metatable field.
737--
738-- @treturn { string... } The (possibly empty) list of completions.
739-- @see shell.setCompletionFunction
740-- @see read
741-- @usage textutils.complete( "pa", getfenv() )
742function complete(sSearchText, tSearchTable)
743 expect(1, sSearchText, "string")
744 expect(2, tSearchTable, "table", "nil")
745
746 if g_tLuaKeywords[sSearchText] then return tEmpty end
747 local nStart = 1
748 local nDot = string.find(sSearchText, ".", nStart, true)
749 local tTable = tSearchTable or _ENV
750 while nDot do
751 local sPart = string.sub(sSearchText, nStart, nDot - 1)
752 local value = tTable[sPart]
753 if type(value) == "table" then
754 tTable = value
755 nStart = nDot + 1
756 nDot = string.find(sSearchText, ".", nStart, true)
757 else
758 return tEmpty
759 end
760 end
761 local nColon = string.find(sSearchText, ":", nStart, true)
762 if nColon then
763 local sPart = string.sub(sSearchText, nStart, nColon - 1)
764 local value = tTable[sPart]
765 if type(value) == "table" then
766 tTable = value
767 nStart = nColon + 1
768 else
769 return tEmpty
770 end
771 end
772
773 local sPart = string.sub(sSearchText, nStart)
774 local nPartLength = #sPart
775
776 local tResults = {}
777 local tSeen = {}
778 while tTable do
779 for k, v in pairs(tTable) do
780 if not tSeen[k] and type(k) == "string" then
781 if string.find(k, sPart, 1, true) == 1 then
782 if not g_tLuaKeywords[k] and string.match(k, "^[%a_][%a%d_]*$") then
783 local sResult = string.sub(k, nPartLength + 1)
784 if nColon then
785 if type(v) == "function" then
786 table.insert(tResults, sResult .. "(")
787 elseif type(v) == "table" then
788 local tMetatable = getmetatable(v)
789 if tMetatable and (type(tMetatable.__call) == "function" or type(tMetatable.__call) == "table") then
790 table.insert(tResults, sResult .. "(")
791 end
792 end
793 else
794 if type(v) == "function" then
795 sResult = sResult .. "("
796 elseif type(v) == "table" and next(v) ~= nil then
797 sResult = sResult .. "."
798 end
799 table.insert(tResults, sResult)
800 end
801 end
802 end
803 end
804 tSeen[k] = true
805 end
806 local tMetatable = getmetatable(tTable)
807 if tMetatable and type(tMetatable.__index) == "table" then
808 tTable = tMetatable.__index
809 else
810 tTable = nil
811 end
812 end
813
814 table.sort(tResults)
815 return tResults
816end