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

How to count people inside the sensor radius

Started by KrisRevi, 29 June 2016 - 08:50 AM
KrisRevi #1
Posted 29 June 2016 - 10:50 AM
Hi.

This is my code for a sensor opening door lock system and it's working perfect! BUT i was wondering how i could count the number of entitys/players inside the radius of the sensor and stop the script from running and tell them "s.speak("Only 1 person at a time")"?

sub.question, is it possible to set the radius for the openCCsensor sensor?


os.loadAPI("sensor")
prox = sensor.wrap("left")
s = peripheral.wrap("right")
while true do
local targets = prox.getTargets()
local moreDetails = prox.getTargetDetails(name)
s.speak("Please step onto marked area and stand still")
sleep(5)
for name, basicDetails in pairs(targets) do
 
  s.speak("Scanning Entity")
  sleep(3)
 
  if name == "KrisRevi" then
  s.speak("Access Granted, welcome KrisRevi")
  sleep(10)
  elseif name == "UNLEASHED91" then
  s.speak("Access Granted, welcome Unleashed")
  sleep(10)
  end
 
end
end
LBPHacker #2
Posted 29 June 2016 - 06:00 PM
I can't see how that'd be "working perfectly", as the variable name doesn't seem to be set when it's passed to .getTargetDetails on line 6.

In any case, you'd count the targets the same way you iterate them, except you'd increment a counter instead of checking their names.
local target_count = 0
for name, basicDetails in pairs(targets) do
	target_count = target_count + 1
end

Then you'd only let through anyone if target_count was 1.

There's also room for optimization in your code. You could just have a table at the top that'd hold all the players to whom access is to be granted, and the infinite loop should iterate over that table and check its entries against targets.
Edited on 29 June 2016 - 04:04 PM