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

[LUA]Dynamic Variable Names (Peripherals)

Started by Lost Ninja, 23 January 2013 - 05:21 AM
Lost Ninja #1
Posted 23 January 2013 - 06:21 AM
I want to create a program that will in part check each side of the computer and discover what peripherals are attached.

Then for it to output each peripheral as a variable name with the side it's attached to as the value.

I've read up on dynamic variable names but I'm not really sure what I'm reading… :/



sSides = {(redstone.getSides())}
perifs = {}
for k, v in pairs(sSides) do
	perifs[v] = (peripheral.getType()) -- <<-- This is line 15 btw <<
end
I get an error @ line 15 expected string.

Is there either a simple way to to do what I want or an API that I can add that adds this easily… I just want to enumerate my peripherals easily and quickly and not need to bother with it again. :/
KaoS #2
Posted 23 January 2013 - 06:42 AM

local periphs = {}
for k, v in pairs(rs.getSides()) do
  if peripheral.isPresent(v) then
	periphs[v]=peripheral.wrap(v)
  end
end

that is basically what you need. the mistake you made is peripheral.getType() should be peripheral.getType(v) so it knows to check that side for the peripheral type.

the above code will make a local table periphs that has all of your peripherals in it, for example if you had a monitor on top of the computer after running the code you could say

periphs.top.write("hi")
to write to the monitor

the problem with this code is that it only checks the peripherals once, if you change your peripherals after that it will not work (if you break the monitor on top of the computer it will still think it is there)

here is a code that checks every time you use it but you cannot use for loops with it


local periphs=setmetatable({},{__index=function(self,index)
  index=string.lower(index)
  local iscorrectsyntax=false
  for k,v in pairs(rs.getSides()) do
	if v==index then iscorrectsyntax=true end
  end
  if iscorrectsyntax and peripheral.isPresent(index) then
	return peripheral.wrap(index)
  end
end})

EDIT: to make it more foolproof and stop it from erroring if you try to use a peripheral that is not there you could use


local periphs=setmetatable({},{__index=function(self,index)
  index=string.lower(index)
  local iscorrectsyntax=false
  for k,v in pairs(rs.getSides()) do
    if v==index then iscorrectsyntax=true end
  end
  if iscorrectsyntax and peripheral.isPresent(index) then
    return peripheral.wrap(index)
  else
    return setmetatable({},{__index=function(tSelf,index2) return function(...) print("peripheral missing on side "..index..". you tried to call "..index2.." with params: ") print(unpack({...})) end end})
  end
end})
Edited on 23 January 2013 - 05:47 AM