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

search inside a table

Started by ZagKalidor, 04 October 2014 - 06:05 PM
ZagKalidor #1
Posted 04 October 2014 - 08:05 PM
Hey guys,

how do i search for a given string pattern, for example "red", that will output all table-values that have the "red" in it like f.e. "Redstone", "Red Carpet", "Red Glass Pane" etc., but it also has to come up with f.e. "Powered Rail" and "Wired Modem". Think of a search function like in the Minecraft Inventory search, where you type in letters and every item with the string appears, giving less items the more accurate the search string gets.

How do i compare my table values for a given string pattern when my table would looks as follows, just for imagination, not be seen for a real code example

item[1].name = "Redstone"
item[2[.name = "Stone"
item[3].name = "Powered Rail"
etc.
etc.

Thx in advance…
Lyqyd #2
Posted 04 October 2014 - 08:47 PM
A simple string.match is probably all you need to use for this case, and would allow you to open up the power of Lua patterns to those using your program.


local search = "red"
local matches = {}

for i, v in ipairs(item) do
  if string.match(v.name, search) then
    table.insert(matches, v.name)
  end
end
ZagKalidor #3
Posted 04 October 2014 - 10:35 PM
Very nice, thanks a lot.
Nice to see, that i was on the right road to this, it just seems, the road was on another planet