Search code examples
regexluaminecraftlua-tablelua-patterns

Print value from a lua table if pattern matches


Okay, so I just recently got into lua and find myself stuck with the following:

I have the function peripheral.getNames() (which is a custom function)

it will return a table with the structure key,value, whereas key is always a number and starts from 1 and value will be what the function finds (it searches for devices connected to it)

In my example it creates a table which looks like this

1 herp
2 derp
3 monitor_1
4 morederp

I can print the values with the following

local pgn = peripherals.getNames()

for key,value in pairs(pgn) do
 setCursorPos(1,key)
 write(value)
 end
end

this will output the corresponding value of the table at key on my display like this

herp
derp
monitor_1
morederp

now, I try to filter my results so it only prints something if value contains 'monitor'

I tried to achive this with

for key,value in pairs(pgn) do
 if string.match(value, monitor) then
 #dostuff
 end
end

but it always returns 'bad argument: string expected, got nil' so obviously string.match either does not accept 'value' or, value is not a string so i tried converting value first

for key,value in pairs(pgn) do
 value = tostring(value)
  if ....
 #dostuff
 end
end

but it still throws the same error

Do any of you have an idea how i might either get string.match to accept 'value' or if there is another method to check the contents of 'value' for a pattern while in this for loop?


Solution

  • The error message is talking about the variable monitor, which is not defined and so has a nil value.

    Try string.match(value, "monitor").