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

create function/API ingame with parameters

Started by Bolrik, 15 September 2012 - 05:38 PM
Bolrik #1
Posted 15 September 2012 - 07:38 PM
Hey guys,

I play on a SMP Server so i don't have access to the file via explorer so i decided to write the function/api ingame.

Okay, what i tried:

'Open turtle with righ click'
-> edit runf
–Code …

i know 1 solution would be to read out the arguments but that's not what i want to..



What i want is something like this:

'Open turtle with right click'
-> runf(10)
*turtle moves 10 blocks*


Hope u understand me =(
greetings
Bubba #2
Posted 15 September 2012 - 08:17 PM
Are you asking for a way to be able to make an api without putting it in the apis folder? Because if you are, then all you need to do is write your api and then call it with os.loadAPI(). Full documentation here.
Bolrik #3
Posted 15 September 2012 - 08:33 PM
I more want to be able to open my turtle and type i.e. runf(10)
(in my case a program i did with 'edit' inside the turtle)


function runf(amount)
x = amount
while x > 0 do
turtle.forward()
x=x-1
end
end

but it says "No such program" but if i type runf it works but without any effect.
MysticT #4
Posted 15 September 2012 - 08:36 PM
I guess you want to write programs that accept arguments, right?
If it's that, you can do it like this:

local tArgs = { ... }
print("The arguments are:")
for _,arg in ipairs(tArgs) do
  print(arg)
end

if tArgs[1] == "Something" then
  print("Doing something here...")
end
The … represents the arguments, so the first line puts all the arguments into a table (tArgs), then you just use them from that table.

Apis can't have arguments. But api functions can:

function doSomething(arg1, arg2)
  -- do something here
end
But you need to use it from a program, not the command line. Like this:

os.loadAPI("myApi")
myApi.doSomething(10, "Hello")
Bolrik #5
Posted 15 September 2012 - 08:43 PM
I think what i was trying is impossible.
I'll try it with arguments then.


Thanks
MysticT #6
Posted 15 September 2012 - 08:48 PM
You were trying to call a function from the console, but you can't. You have to make a program that calls the functions, and give the parameters to the program like I said.
Example:

local tArgs = { ... }
if #tArgs ~= 1 then
  print("Usage: runf <amount>")
  return
end

local n = tonumber(tArgs[1])
for i = 1, n do
  turtle.forward()
end
Then you use it like:
> runf 10
to move the turtle 10 blocks forward.