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

turtleAPI short commands [quite simple interpreter]

Started by Conan1981m, 07 June 2013 - 12:36 PM
Conan1981m #1
Posted 07 June 2013 - 02:36 PM
Hey,

Ive just discovered the go program (/rom/programs/turtles/go)
and thought, this is great and could be expanded ..
So i added the action parts to a file with mostly shorten commands.

Some guys may say it is useless but i admit :

it shortens the Code,
in this case it shortens the misspellings
it is easy to understand
you can just set the amount of the commands

aaand most of all, if you have programmed a lot of stuff and there might be some changes in the code,
there is one spot to change it for any file you did with it.

tell me what you think.

http://pastebin.com/fLybSXAT


pastebin get fLybSXAT act

ps.: Sorry for my bad english
ElvishJerricco #2
Posted 09 June 2013 - 04:25 AM
Why not just


local args = { ... }
for i,v in ipairs(args) do
	args[i] = tonumber(v) or v -- if the argument can be a number, make it so!
end
local func = table.remove(args, 1) -- keep function name separate so that a simple unpack() will do for function arguments.
turtle[func](unpack(args))

Or better yet, if you want to make it more like a live interpreter like the "lua" program,


function processStr(str)
	local cmd = {}
	for w in str:gmatch("%w+") do
		local c = tonumber(w) or w
		table.insert(cmd, c)
	end
	local func = table.remove(cmd, 1)
	assert(turtle[func], "No such command")
	local ret = { turtle[func](unpack(cmd)) }
	for i,v in ipairs(ret) do
		ret[i] = tostring(v)
	end
	print(table.concat(ret, "\n"))
end

local cmdHistory = {}
while true do
	-- Using pcall to make erroring easier in the processing function.
	-- Also means that should a turtle function error, it is no problem.
	write("> ")
	local ok, err = pcall(processStr, read(nil, cmdHistory))
	if not ok then printError(err) end
end