[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: autocompletion code
- From: Dimitris Papavasiliou <jimmyp@...>
- Date: Mon, 26 Apr 2004 03:51:55 +0300
I've written this code which, given a lua command line in a string (s)
and a cursor position (i) finds all candidate table keys to complete the
command at the position. It completes table indexing expressions of the
form 'table.keyprefix'. (hmmmm, now that I think of it, since I use
loadstring to parse the to-be-indexed table expression, with a little
pattern tweaking I might be able to make it possible for 'table' in
'table.keyprefix' to be anything, like say a function call and not just
an expression of the form "foo.bar. ... .xyz". I'll look into this...)
Anyway since this is my first attempt at string processing lua code (or
any non-trivial lua code for that matter) I'm sure there are better ways
to do some things. I'm not (particularly) interested in speed, more in
better code. I'm especially looking for better ways to:
a) find the substring I need to parse (the first while loop).
b) if possible when breaking sub into path and prefix use a pattern that
will return "" for path and the whole string sub for prefix if the
string sub contains no dots. Then I can get rid of the if statement
afterwards and use something like table = assert(loadstring("return " ..
path))() or nil instead.
Any suggestrions are welcome.
Thanks in advance,
PS: oh, almost forgot, the code (btw I know there's lots of error
checking that needs to be done, but this is not important right now):
-- the command and cursor position
s = "print(string."
i = string.len(s)
-- scan the string backwards starting at the cursor to find the substring
-- we're interested in (sub)
while string.find(string.sub(s, i, i), "[%w_\.]") do
sub = string.sub(s, i, i) .. (sub or "")
i = i - 1
local i, j, prefix, path, table
-- break a string of the form "foo.bar.pre" into "foo.bar" (path) and
-- "pre" (prefix).
i, j, path, prefix = string.find(sub, "([%w_%.]+)%.([%w_]*)")
-- if there were no dots in the string then the table from wich to complete
-- is _G and the prefix is the whole string
if(path == nil) then
table = _G
prefix = sub
-- else get the table represented by path
table = assert(loadstring("return " .. path))()
-- now look up all keys in table starting with (but different from)
prefix and print them
for k in pairs(table) do
if string.find(k, "^" .. prefix .. ".+") then