This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
MR_nesquick's profile picture

Compare character

Started by MR_nesquick, 18 July 2013 - 03:49 PM
MR_nesquick #1
Posted 18 July 2013 - 05:49 PM
is there a way to compare a character in the middle of a string?
i'm making a search bar and it only shows the first character in the string when a search for it

Spoiler

Search = true
searchBar = {
"hello",
"how",
"does",
"this",
"work",
"test"
}
while Search == true do
_,input = os.pullEvent("char")
print(input)
for i = 1,#searchBar do
_,_,str = string.find(searchBar[i],"(.)")
  if input == str then
   searching = searchBar[i]
   print(searching)
  end
end
if input == "Q" then
Search = false
end
end
if i type "e" i would like to have the string "hello","does","test" showing
LBPHacker #2
Posted 18 July 2013 - 05:58 PM
You could use string.find for that:
local entries = {
    "hello",
    "how",
    "does",
    "this",
    "work",
    "test"
}

local searchInEntries = function(key)
    -- * will return a table of entries which contain the key
    local result = {}
    for ixEnt = 1, #entries do if string.find(entries[ixEnt], key) then table.insert(result, entries[ixEnt]) end end
    return result
end
More at http://lua-users.org/wiki/StringLibraryTutorial
Engineer #3
Posted 18 July 2013 - 06:45 PM
Ive made the code. Lets say I was bored :)/>
Spoiler


local entries = {
  "stuff";
  "test"
}

local showStr = ""
term.clear()
term.setCursorPos( 1, 1 )
term.setCursorBlink( true )

local display = function()
	term.clear()
	term.setCursorPos( 1, 2 )
	for k, v in pairs( entries ) do
		if v:find( (function( str )
			local safePat = ""
			local mChars = {
				["*"] = true; ["+"] = true; ["-"] = true;
				["["] = true; ["]"] = true; ["."] = true;
				["("] = true; [")"] = true; ["%"] = true;
				["$"] = true; ["^"] = true; ["?"] = true;
			}
			for i = 1, str:len() do
				if mChars[str:sub( i, i )] then
					safePat = safePat .. "%" .. str:sub( i, i )
				else
					safePat = safePat .. str:sub( i, i )
				end
			end
			return safePat
		end)( showStr )) then
			print( v )
		end
	end

	term.setCursorPos( 1, 1 )
	term.clearLine()
	term.write( showStr )
end

while true do
	local e = {os.pullEvent()}
	if e[1] == "char" then
		showStr = showStr .. e[2]
		display()
	elseif e[1] == "key" then
		if e[2] == keys.enter then
			break
		elseif e[2] == keys.backspace then
			showStr = showStr:sub( 1, showStr:len() - 1 )
			display()
			if ({term.getCursorPos()})[1] == 1 then
				term.clear()
				term.setCursorPos( 1, 1 )
			end
		end
	end
end

Not sure if its always 100% correct!
MR_nesquick #4
Posted 18 July 2013 - 06:51 PM
wow. thanks