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

[SOLVED] Passing function arguments to APIs

Started by ForTheKremlin, 30 March 2013 - 01:57 PM
ForTheKremlin #1
Posted 30 March 2013 - 02:57 PM
I'm having a few issues with passing variables as arguments to functions in APIs. Take for example the following program, named testCheck

os.loadAPI("check")
local tArgs = { ... }
var = tonumber(tArgs[1])
if check.positive(var) == false then
  print("var must be positive!")
  return
end
print("success!")

In the API named check, I have the following code.

local function positive(var)
  if var < 0 then
	return false
  else
	return true
  end
end

For some reason, whenever I run

testCheck 3
I get the message:

testCheck:4: attempt to call nil

However, when I run this program:

local function positive(var)
  if var < 0 then
	return false
  else
	return true
  end
end

local tArgs = { ... }
var = tonumber(tArgs[1])

if positive(var) == false then
  print("var must be positive!")
  return
end

print("success!")
I get the desired result – prints "var must be positive!" if I supply -3 as an argument, and prints "success!" if I give 3 as an argument. The programs are essentially the same, except one uses an API and the other doesn't. So how can I use an API and still get the same result?
faubiguy #2
Posted 30 March 2013 - 03:00 PM
Local functions in APIs can only be called from within the API. If you want an API function to be accessible from other programs, it needs to not be declared as local..
ForTheKremlin #3
Posted 30 March 2013 - 03:07 PM
Local functions in APIs can only be called from within the API. If you want an API function to be accessible from other programs, it needs to not be declared as local..
Thanks!