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

Code not working

Started by ebernerd, 20 December 2014 - 03:50 AM
ebernerd #1
Posted 20 December 2014 - 04:50 AM
This code was working the last time I had this save installed. I came back to show my dad, and it doesn't work anymore.

API Code:

local function rsOpen(side)
  if side == nil then
	for i,v in pairs(rs.getSides()) do
	  if peripheral.getType(v) == "modem" then
		rednet.open(v)
	  end
	end
  else
	rednet.open(side)
  end
end

local function rsClose(side)
  if side == nil then
	for i,v in pairs(rs.getSides()) do
	  if peripheral.getType(v) == "modem" then
		rednet.close(v)
	  end
	end
  else
	rednet.close(side)
  end
end

Program Code:


os.loadAPI("m") --file where api is located
m.rsOpen("top")

Can anyone tell me what's up? My error is:

test:2: attempt to call nil
Edited on 20 December 2014 - 03:51 AM
KingofGamesYami #2
Posted 20 December 2014 - 05:14 AM
The problem is you defined your functions locally. While normally this is an excellent idea (local variables are faster), you have to define the globally when you use an API.


function abc() --# this can be accessed
  --#bla bla bla
end
local function cba() --# this cannot
  --#bla bla bla
end
ebernerd #3
Posted 20 December 2014 - 01:29 PM
The problem is you defined your functions locally. While normally this is an excellent idea (local variables are faster), you have to define the globally when you use an API.


function abc() --# this can be accessed
  --#bla bla bla
end
local function cba() --# this cannot
  --#bla bla bla
end

Aah, yes. Thank you. I've just gotten into the habit of defining things locally, but I guess I can't here. Thank you.
TheOddByte #4
Posted 20 December 2014 - 07:30 PM
Aah, yes. Thank you. I've just gotten into the habit of defining things locally, but I guess I can't here. Thank you.
I wouldn't call it a bad habit, it's just a problem when you're creating an API and try to make a function local.
You can ofcourse create local functions in an API that other functions can use

local function bar()
    print( "Hello World!" )
end

function foo()
    bar()
end
This can be helpful if you want a user not being able to directly call a function that wouldn't work on it's own.