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

Error.Help me to find it

Started by JetFly, 18 May 2017 - 06:38 PM
JetFly #1
Posted 18 May 2017 - 08:38 PM
Sorry,i was looking to myself like <snip> this while writing the title =D
The problem is with turtle control server program.All it does it controls turtles via Rednet.When trying to execute server it halts my pc.(minecraft pc,for others who didn';t understand)
Code:
rednet.broadcast("1");
while true do
	if (keys.w == true) then
		rednet.broadcast("w") // forward
	end
	if(keys.a == true) then
		rednet.broadcast("a") // left
	end
	if(keys.s == true) then
		rednet.broadcast("s") // back
	end
	if(keys.d == true) then
		rednet.broadcast("d") // right
	end
	if(keys.q == true) then
		rednet.broadcast("q") // down
	end
	if(keys.e == true) then
		rednet.broadcast("e") // up
	end
end
I love the formatting of programming languages, it';s useful.I'm a code monkey.But,only in Lua.Does anyone know C# to Lua converter compatible with CC?
Edited by
Bomb Bloke #2
Posted 19 May 2017 - 01:08 AM
ComputerCraft is event-driven; all our code runs within a coroutine, which is resumed whenever events occur. The values you've found in the "keys" API table represent events that can happen, but on their own give no indication as to whether those events have happened - you need to pull data from the event queue in order to figure that out (ie, yield our code until CC has an event with which to resume it). For this we use os.pullEvent():

peripheral.find("modem", rednet.open)  -- Readies all attached modems.

rednet.broadcast("1")

while true do
	local event, key = os.pullEvent("key")  -- Yield (do nothing) until a key event occurs.
	
	if key == keys.w then
		rednet.broadcast("w") -- forward
	elseif key == keys.a then
		rednet.broadcast("a") -- left
	elseif key == keys.s then
		rednet.broadcast("s") -- back
	elseif key == keys.d then
		rednet.broadcast("d") -- right
	elseif key == keys.q then
		rednet.broadcast("q") -- down
	elseif key == keys.e then
		rednet.broadcast("e") -- up
	end
end

The code can be simplified using tables:

peripheral.find("modem", rednet.open)  -- Readies all attached modems.

rednet.broadcast("1")

local keys = {keys.w = true, keys.a = true, keys.s = true, keys.d = true, keys.q = true, keys.e = true}

while true do
	local event, key = os.pullEvent("key")
	
	-- If an element exists in the keys table corresponding to the keycode pressed, broadcast that key's name:
	if keys[key] then rednet.broadcast(keys.getName(key)) end
end