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

Attempt to index ? (a nil value)

Started by gheotic, 27 October 2015 - 07:10 AM
gheotic #1
Posted 27 October 2015 - 08:10 AM
Where is the problem in this program?
Here is a link to the documentation for the peripheral i use.



local p = peripheral.wrap("left")
while true do
   sleep(0.5)
   if p.getNearbyPlayers(5)[1] == nil then
	  redstone.setOutput("bottom", false)
   else
	  name = p.getNearbyPlayers(5)[1]["player"] --This is where it fails
	  if name == "tilde1000" then
		 redstone.setOutput("bottom", true)
	   end
   end
end  
SquidDev #2
Posted 27 October 2015 - 09:49 AM
If this bit is erroring:

p.getNearbyPlayers(5)[1]["player"]

Then one of these is nil:

p.getNearbyPlayers(5)
p.getNearbyPlayers(5)[1]

The easiest thing to do would be to check each one to see if it is nil:

local players = p.getNearbyPlayers(5)
if players ~= nil and players[1] ~= nil then
  print(players[1]["player"])
end

You might also want to loop through every possible player:

for _, player in ipairs(p.getNearbyPlayers(5)) do
  print(player["player"])
end
Edited on 27 October 2015 - 08:49 AM
gheotic #3
Posted 27 October 2015 - 11:10 AM
If this bit is erroring:

p.getNearbyPlayers(5)[1]["player"]

Then one of these is nil:

p.getNearbyPlayers(5)
p.getNearbyPlayers(5)[1]

The easiest thing to do would be to check each one to see if it is nil:

local players = p.getNearbyPlayers(5)
if players ~= nil and players[1] ~= nil then
  print(players[1]["player"])
end

You might also want to loop through every possible player:

for _, player in ipairs(p.getNearbyPlayers(5)) do
  print(player["player"])
end

Thanks works like charm!