Print value from a lua table if pattern matches

◇◆丶佛笑我妖孽 提交于 2020-01-04 14:21:24

问题


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?


回答1:


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

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



来源:https://stackoverflow.com/questions/25252653/print-value-from-a-lua-table-if-pattern-matches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!