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

[Lua][Programming] Key Input?

Started by TheEisbaer, 20 October 2012 - 03:22 PM
TheEisbaer #1
Posted 20 October 2012 - 05:22 PM
Hey guys,

how do I "code" something that's like: I press Arrow Left it says prints Hi?

Thanks

TheEisbaer
faubiguy #2
Posted 20 October 2012 - 05:53 PM
Use os.pullEvent to detect events, including keypresses
local event, key = os.pullEvent("key")
if key = keys.left then
    print("Hi")
end

You can use os.pullEvent() without any argument to get all events, like redstone, keys, and rednet.
TheEisbaer #3
Posted 20 October 2012 - 05:59 PM
Do you know how I make a Turtle Do Something if i send it something with rednet? D:
ChunLing #4
Posted 20 October 2012 - 06:16 PM
There are a number of remote control programs for turtles that use different methods. I recommend:
while rcID do sndr,rnmssg = rednet.receive()
        if sndr == rcID then
            _,_,cmnd, prm1 = rnmssg:find("^(%a+)(.*)")
            if turtle[cmnd] then turtle[cmnd](tonumber(prm1))
       	 elseif rnmssg == "trmn8RC" then rcID = nil end
        end
end
rcID is the ID of the controller for the turtle, sndr is the ID of a rednet message, rnmssg is the message. If the message is from the correct ID, then parse the message into a command (cmnd) and parameter (prm1). If the command is a turtle API function, then execute that command with the parameter (after converting it to a number). Of note, you only need to send the part of the function name that comes after 'turtle.'. So to do turtle.forward(), just send "forward". The parameter isn't used for most functions, but when it should be a number. You can separate the number from the command with a space (or not). So "select 8" will call turtle.select(8) and then "drop 10" will call turtle.drop(10).

If the message didn't parse as a turtle function, then check if it was the terminate command to end remote control.