如果模式匹配,则从lua表中打印值 [英] Print value from a lua table if pattern matches

查看:98
本文介绍了如果模式匹配,则从lua表中打印值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我最近刚进入lua,发现自己陷入了以下困境:

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

我有函数peripheral.getNames()(这是一个自定义函数)

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

它将返回具有键,值结构的表,而键始终是一个数字,从1开始,而值将是该函数所找到的值(它将搜索与其连接的设备)

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'

我试图做到这一点

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

,但它始终返回错误的参数:期望的字符串,没有nil" 所以很明显string.match不接受'value'或value不是字符串 所以我尝试先转换值

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

你们中有谁知道我可能如何让string.match接受值",或者在此for循环中是否存在另一种方法来检查模式的值"的内容?

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?

推荐答案

错误消息正在谈论变量monitor,该变量未定义,因此具有nil值.

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

尝试string.match(value, "monitor").

这篇关于如果模式匹配,则从lua表中打印值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆