· 5 years ago · Oct 29, 2020, 08:04 AM
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, 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 function serializeJSONImpl(t, tTracking, bNBTStyle)
339 local sType = type(t)
340 if t == empty_json_array then return "[]"
341 elseif t == json_null then return "null"
342
343 elseif sType == "table" then
344 if tTracking[t] ~= nil then
345 error("Cannot serialize table with recursive entries", 0)
346 end
347 tTracking[t] = true
348
349 if next(t) == nil then
350 -- Empty tables are simple
351 return "{}"
352 else
353 -- Other tables take more work
354 local sObjectResult = "{"
355 local sArrayResult = "["
356 local nObjectSize = 0
357 local nArraySize = 0
358 for k, v in pairs(t) do
359 if type(k) == "string" then
360 local sEntry
361 if bNBTStyle then
362 sEntry = tostring(k) .. ":" .. serializeJSONImpl(v, tTracking, bNBTStyle)
363 else
364 sEntry = string.format("%q", k) .. ":" .. serializeJSONImpl(v, tTracking, bNBTStyle)
365 end
366 if nObjectSize == 0 then
367 sObjectResult = sObjectResult .. sEntry
368 else
369 sObjectResult = sObjectResult .. "," .. sEntry
370 end
371 nObjectSize = nObjectSize + 1
372 end
373 end
374 for _, v in ipairs(t) do
375 local sEntry = serializeJSONImpl(v, tTracking, bNBTStyle)
376 if nArraySize == 0 then
377 sArrayResult = sArrayResult .. sEntry
378 else
379 sArrayResult = sArrayResult .. "," .. sEntry
380 end
381 nArraySize = nArraySize + 1
382 end
383 sObjectResult = sObjectResult .. "}"
384 sArrayResult = sArrayResult .. "]"
385 if nObjectSize > 0 or nArraySize == 0 then
386 return sObjectResult
387 else
388 return sArrayResult
389 end
390 end
391
392 elseif sType == "string" then
393 return string.format("%q", t)
394
395 elseif sType == "number" or sType == "boolean" then
396 return tostring(t)
397
398 else
399 error("Cannot serialize type " .. sType, 0)
400
401 end
402end
403
404local unserialise_json
405do
406 local sub, find, match, concat, tonumber = string.sub, string.find, string.match, table.concat, tonumber
407
408 --- Skip any whitespace
409 local function skip(str, pos)
410 local _, last = find(str, "^[ \n\r\v]+", pos)
411 if last then return last + 1 else return pos end
412 end
413
414 local escapes = {
415 ["b"] = '\b', ["f"] = '\f', ["n"] = '\n', ["r"] = '\r', ["t"] = '\t',
416 ["\""] = "\"", ["/"] = "/", ["\\"] = "\\",
417 }
418
419 local mt = {}
420
421 local function error_at(pos, msg, ...)
422 if select('#', ...) > 0 then msg = msg:format(...) end
423 error(setmetatable({ pos = pos, msg = msg }, mt))
424 end
425
426 local function expected(pos, actual, exp)
427 if actual == "" then actual = "end of input" else actual = ("%q"):format(actual) end
428 error_at(pos, "Unexpected %s, expected %s.", actual, exp)
429 end
430
431 local function parse_string(str, pos)
432 local buf, n = {}, 1
433
434 while true do
435 local c = sub(str, pos, pos)
436 if c == "" then error_at(pos, "Unexpected end of input, expected '\"'.") end
437 if c == '"' then break end
438
439 if c == '\\' then
440 -- Handle the various escapes
441 c = sub(str, pos + 1, pos + 1)
442 if c == "" then error_at(pos, "Unexpected end of input, expected escape sequence.") end
443
444 if c == "u" then
445 local num_str = match(str, "^%x%x%x%x", pos + 2)
446 if not num_str then error_at(pos, "Malformed unicode escape %q.", sub(str, pos + 2, pos + 5)) end
447 buf[n], n, pos = utf8.char(tonumber(num_str, 16)), n + 1, pos + 6
448 else
449 local unesc = escapes[c]
450 if not unesc then error_at(pos + 1, "Unknown escape character %q.", unesc) end
451 buf[n], n, pos = unesc, n + 1, pos + 2
452 end
453 elseif c >= '\x20' then
454 buf[n], n, pos = c, n + 1, pos + 1
455 else
456 error_at(pos + 1, "Unescaped whitespace %q.", c)
457 end
458 end
459
460 return concat(buf, "", 1, n - 1), pos + 1
461 end
462
463 local valid = { b = true, B = true, s = true, S = true, l = true, L = true, f = true, F = true, d = true, D = true }
464 local function parse_number(str, pos, opts)
465 local _, last, num_str = find(str, '^(-?%d+%.?%d*[eE]?[+-]?%d*)', pos)
466 local val = tonumber(num_str)
467 if not val then error_at(pos, "Malformed number %q.", num_str) end
468
469 if opts.nbt_style and valid[sub(str, pos + 1, pos + 1)] then return val, last + 2 end
470
471 return val, last + 1
472 end
473
474 local function parse_ident(str, pos)
475 local _, last, val = find(str, '^([%a][%w_]*)', pos)
476 return val, last + 1
477 end
478
479 local function decode_impl(str, pos, opts)
480 local c = sub(str, pos, pos)
481 if c == '"' then return parse_string(str, pos + 1)
482 elseif c == "-" or c >= "0" and c <= "9" then return parse_number(str, pos, opts)
483 elseif c == "t" then
484 if sub(str, pos + 1, pos + 3) == "rue" then return true, pos + 4 end
485 elseif c == 'f' then
486 if sub(str, pos + 1, pos + 4) == "alse" then return false, pos + 5 end
487 elseif c == 'n' then
488 if sub(str, pos + 1, pos + 3) == "ull" then
489 if opts.parse_null then
490 return json_null, pos + 4
491 else
492 return nil, pos + 4
493 end
494 end
495 elseif c == "{" then
496 local obj = {}
497
498 pos = skip(str, pos + 1)
499 c = sub(str, pos, pos)
500
501 if c == "" then return error_at(pos, "Unexpected end of input, expected '}'.") end
502 if c == "}" then return obj, pos + 1 end
503
504 while true do
505 local key, value
506 if c == "\"" then key, pos = parse_string(str, pos + 1)
507 elseif opts.nbt_style then key, pos = parse_ident(str, pos)
508 else return expected(pos, c, "object key")
509 end
510
511 pos = skip(str, pos)
512
513 c = sub(str, pos, pos)
514 if c ~= ":" then return expected(pos, c, "':'") end
515
516 value, pos = decode_impl(str, skip(str, pos + 1), opts)
517 obj[key] = value
518
519 -- Consume the next delimiter
520 pos = skip(str, pos)
521 c = sub(str, pos, pos)
522 if c == "}" then break
523 elseif c == "," then pos = skip(str, pos + 1)
524 else return expected(pos, c, "',' or '}'")
525 end
526
527 c = sub(str, pos, pos)
528 end
529
530 return obj, pos + 1
531
532 elseif c == "[" then
533 local arr, n = {}, 1
534
535 pos = skip(str, pos + 1)
536 c = sub(str, pos, pos)
537
538 if c == "" then return expected(pos, c, "']'") end
539 if c == "]" then return empty_json_array, pos + 1 end
540
541 while true do
542 n, arr[n], pos = n + 1, decode_impl(str, pos, opts)
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 end
552
553 return arr, pos + 1
554 elseif c == "" then error_at(pos, 'Unexpected end of input.')
555 end
556
557 error_at(pos, "Unexpected character %q.", c)
558 end
559
560 --- Converts a serialised JSON string back into a reassembled Lua object.
561 --
562 -- This may be used with @{textutils.serializeJSON}, or when communicating
563 -- with command blocks or web APIs.
564 --
565 -- @tparam string s The serialised string to deserialise.
566 -- @tparam[opt] { nbt_style? = boolean, parse_null? = boolean } options
567 -- Options which control how this JSON object is parsed.
568 --
569 -- - `nbt_style`: When true, this will accept [stringified NBT][nbt] strings,
570 -- as produced by many commands.
571 -- - `parse_null`: When true, `null` will be parsed as @{json_null}, rather
572 -- than `nil`.
573 --
574 -- [nbt]: https://minecraft.gamepedia.com/NBT_format
575 -- @return[1] The deserialised object
576 -- @treturn[2] nil If the object could not be deserialised.
577 -- @treturn string A message describing why the JSON string is invalid.
578 unserialise_json = function(s, options)
579 expect(1, s, "string")
580 expect(2, options, "table", "nil")
581
582 if options then
583 field(options, "nbt_style", "boolean", "nil")
584 field(options, "nbt_style", "boolean", "nil")
585 else
586 options = {}
587 end
588
589 local ok, res, pos = pcall(decode_impl, s, skip(s, 1), options)
590 if not ok then
591 if type(res) == "table" and getmetatable(res) == mt then
592 return nil, ("Malformed JSON at position %d: %s"):format(res.pos, res.msg)
593 end
594
595 error(res, 0)
596 end
597
598 pos = skip(s, pos)
599 if pos <= #s then
600 return nil, ("Malformed JSON at position %d: Unexpected trailing character %q."):format(pos, sub(s, pos, pos))
601 end
602 return res
603
604 end
605end
606
607--- Convert a Lua object into a textual representation, suitable for
608-- saving in a file or pretty-printing.
609--
610-- @param t The object to serialise
611-- @treturn string The serialised representation
612-- @throws If the object contains a value which cannot be
613-- serialised. This includes functions and tables which appear multiple
614-- times.
615function serialize(t)
616 local tTracking = {}
617 return serializeImpl(t, tTracking, "")
618end
619
620serialise = serialize -- GB version
621
622--- Converts a serialised string back into a reassembled Lua object.
623--
624-- This is mainly used together with @{textutils.serialize}.
625--
626-- @tparam string s The serialised string to deserialise.
627-- @return[1] The deserialised object
628-- @treturn[2] nil If the object could not be deserialised.
629function unserialize(s)
630 expect(1, s, "string")
631 local func = load("return " .. s, "unserialize", "t", {})
632 if func then
633 local ok, result = pcall(func)
634 if ok then
635 return result
636 end
637 end
638 return nil
639end
640
641unserialise = unserialize -- GB version
642
643--- Returns a JSON representation of the given data.
644--
645-- This function attempts to guess whether a table is a JSON array or
646-- object. However, empty tables are assumed to be empty objects - use
647-- @{textutils.empty_json_array} to mark an empty array.
648--
649-- This is largely intended for interacting with various functions from the
650-- @{commands} API, though may also be used in making @{http} requests.
651--
652-- @param t The value to serialise. Like @{textutils.serialise}, this should not
653-- contain recursive tables or functions.
654-- @tparam[opt] boolean bNBTStyle Whether to produce NBT-style JSON (non-quoted keys)
655-- instead of standard JSON.
656-- @treturn string The JSON representation of the input.
657-- @throws If the object contains a value which cannot be
658-- serialised. This includes functions and tables which appear multiple
659-- times.
660-- @usage textutils.serializeJSON({ values = { 1, "2", true } })
661function serializeJSON(t, bNBTStyle)
662 expect(1, t, "table", "string", "number", "boolean")
663 expect(2, bNBTStyle, "boolean", "nil")
664 local tTracking = {}
665 return serializeJSONImpl(t, tTracking, bNBTStyle or false)
666end
667
668serialiseJSON = serializeJSON -- GB version
669
670unserializeJSON = unserialise_json
671unserialiseJSON = unserialise_json
672
673--- Replaces certain characters in a string to make it safe for use in URLs or POST data.
674--
675-- @tparam string str The string to encode
676-- @treturn string The encoded string.
677-- @usage print("https://example.com/?view=" .. textutils.urlEncode(read()))
678function urlEncode(str)
679 expect(1, str, "string")
680 if str then
681 str = string.gsub(str, "\n", "\r\n")
682 str = string.gsub(str, "([^A-Za-z0-9 %-%_%.])", function(c)
683 local n = string.byte(c)
684 if n < 128 then
685 -- ASCII
686 return string.format("%%%02X", n)
687 else
688 -- Non-ASCII (encode as UTF-8)
689 return
690 string.format("%%%02X", 192 + bit32.band(bit32.arshift(n, 6), 31)) ..
691 string.format("%%%02X", 128 + bit32.band(n, 63))
692 end
693 end)
694 str = string.gsub(str, " ", "+")
695 end
696 return str
697end
698
699local tEmpty = {}
700
701--- Provides a list of possible completions for a partial Lua expression.
702--
703-- If the completed element is a table, suggestions will have `.` appended to
704-- them. Similarly, functions have `(` appended to them.
705--
706-- @tparam string sSearchText The partial expression to complete, such as a
707-- variable name or table index.
708--
709-- @tparam[opt] table tSearchTable The table to find variables in, defaulting to
710-- the global environment (@{_G}). The function also searches the "parent"
711-- environment via the `__index` metatable field.
712--
713-- @treturn { string... } The (possibly empty) list of completions.
714-- @see shell.setCompletionFunction
715-- @see read
716-- @usage textutils.complete( "pa", getfenv() )
717function complete(sSearchText, tSearchTable)
718 expect(1, sSearchText, "string")
719 expect(2, tSearchTable, "table", "nil")
720
721 if g_tLuaKeywords[sSearchText] then return tEmpty end
722 local nStart = 1
723 local nDot = string.find(sSearchText, ".", nStart, true)
724 local tTable = tSearchTable or _ENV
725 while nDot do
726 local sPart = string.sub(sSearchText, nStart, nDot - 1)
727 local value = tTable[sPart]
728 if type(value) == "table" then
729 tTable = value
730 nStart = nDot + 1
731 nDot = string.find(sSearchText, ".", nStart, true)
732 else
733 return tEmpty
734 end
735 end
736 local nColon = string.find(sSearchText, ":", nStart, true)
737 if nColon then
738 local sPart = string.sub(sSearchText, nStart, nColon - 1)
739 local value = tTable[sPart]
740 if type(value) == "table" then
741 tTable = value
742 nStart = nColon + 1
743 else
744 return tEmpty
745 end
746 end
747
748 local sPart = string.sub(sSearchText, nStart)
749 local nPartLength = #sPart
750
751 local tResults = {}
752 local tSeen = {}
753 while tTable do
754 for k, v in pairs(tTable) do
755 if not tSeen[k] and type(k) == "string" then
756 if string.find(k, sPart, 1, true) == 1 then
757 if not g_tLuaKeywords[k] and string.match(k, "^[%a_][%a%d_]*$") then
758 local sResult = string.sub(k, nPartLength + 1)
759 if nColon then
760 if type(v) == "function" then
761 table.insert(tResults, sResult .. "(")
762 elseif type(v) == "table" then
763 local tMetatable = getmetatable(v)
764 if tMetatable and (type(tMetatable.__call) == "function" or type(tMetatable.__call) == "table") then
765 table.insert(tResults, sResult .. "(")
766 end
767 end
768 else
769 if type(v) == "function" then
770 sResult = sResult .. "("
771 elseif type(v) == "table" and next(v) ~= nil then
772 sResult = sResult .. "."
773 end
774 table.insert(tResults, sResult)
775 end
776 end
777 end
778 end
779 tSeen[k] = true
780 end
781 local tMetatable = getmetatable(tTable)
782 if tMetatable and type(tMetatable.__index) == "table" then
783 tTable = tMetatable.__index
784 else
785 tTable = nil
786 end
787 end
788
789 table.sort(tResults)
790 return tResults
791end