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

[SOLVED] how do I filter peripherals in list = peripheral.getNames()

Started by qwerty, 19 March 2020 - 10:30 AM
qwerty #1
Posted 19 March 2020 - 11:30 AM
it amuses me that I'm the only one asking for help here.

On to the point, how do I filter a table of contents efficiently?
I have a list of peripherals attached in a table and I have potentially hundreds of peripherals on the network, however, all are not equal.
some are disk drives others are monitors, but I have a table with the peripherals that I need access to, and it looks a lot like this;

list = {
"immersiveengineering:storage_crate",
"minecraft:chest",
"thermalexpansion:storage_cache"
}
and here's a table that has the peripherals attached;

periph = {
"right",
"top",
"immersiveengineering:storage_crate_1",
"minecraft:chest_3"
}

so my question is; how do I determine that periph[item] equals list[any]?
thanks in advance.

with regards,
-qwerty
Edited on 19 March 2020 - 11:43 AM
qwerty #2
Posted 19 March 2020 - 12:43 PM
nvm, a friend helped me out. here's the code anyway;


periphlist = peripheral.getNames()
desired = {
"inset peripheral name here"
}
peripherals = {}

for p=1,#periphlist do
   for t=1,#desired do
      if string.find(periphlist[p],desired[t]) then
       peripherals[#peripherals+1] = periphlist[p]
     end
   end
end
Luca_S #3
Posted 19 March 2020 - 04:32 PM
You should not use string.find() to check if a peripheral is of a certain type, you should change your code to do this(Also make all variables that can be local local):
Edit: Also once you've found that your peripheral is of a desired type and adding it to the peripherals table, there's no need to check for the rest of the peripherals, so you can break after inserting to the peripherals table.

local periphlist = peripheral.getNames()
local desired = {
"inset peripheral name here"
}
local peripherals = {}
for p=1,#periphlist do
   for t=1,#desired do
	  if peripheral.getType(periphlist[p]) == desired[t] then
	   peripherals[#peripherals+1] = periphlist[p]
	   break
	 end
   end
end
Edited on 19 March 2020 - 03:34 PM
qwerty #4
Posted 20 March 2020 - 05:32 AM
ok well thanks.
valithor #5
Posted 25 March 2020 - 02:23 AM
Here is another solution:


list = {
["immersiveengineering:storage_crate"] = true,
["minecraft:chest"] = true,
["thermalexpansion:storage_cache"] = true
}

local periphlist = peripheral.getNames()
local peripherals = {}
for i = 1, #periphlist do
  if list[periphlist[i]] then
    table.insert(peripherals,periphlist[i])
  end
end