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

[SOLVED] Question Regarding Local Functions in APIs

Started by surferpup, 25 January 2014 - 10:21 PM
surferpup #1
Posted 25 January 2014 - 11:21 PM
I wrote my first API, and in attempting to follow good practices, I made all of the functions with the exception of the user-callable functions local. However, I found that doing so caused me some grief, and I ended up having to make one of the internal API functions global.

Here is the scenario:



local function localFuntion()
  problemLocalFunction() <-- this is where the code errors
end

local function problemLocalFunction()
  do
	 --stuff
  end
end

function userFunction()
  localFuntion()
end


When I call the API.userFunction() with the local version of problemLocalFunction, I get the error:


myCoolAPI:<line number of call to problemLocalFunction>: attempt to call nil

When I remove the local keyword from the declaration of problemLocalFunction, everything runs fine.

It seems that I cannot call a local function from within another local function of the API. Can anyone explain this to me?
Edited on 30 January 2014 - 12:53 AM
Bomb Bloke #2
Posted 25 January 2014 - 11:40 PM
Think of your functions as variables, same as the containers you store your strings and numbers and whatnot in.

local function someVariable()
  -- "someVariable" is now storing a(n empty) function.
end

someVariable = 2  -- "someVariable" is now storing a number.

someVariable() -- This'll throw "attempt to call number".

Loosely put, when Lua runs your script the interpreter takes a look at your function definitions and converts them to bytecode (this is what your "function variables" actually point to).

In the event that a function it's reading wants to call another function, Lua looks for that function. If a local version exists, fine, it points to that. If it doesn't, Lua points to a global version. If you don't define a global version then you'll error out with an attempt to call nil.

So: If you try to define a function that calls the local function "problemLocalFunction" before "problemLocalFunction" itself has been defined, you get an error. Same as trying to add "a" to "b" before defining "a" and "b". Declare all local functions before any other functions that make use of them.
Edited on 25 January 2014 - 10:43 PM
surferpup #3
Posted 25 January 2014 - 11:56 PM
Thanks Bomb Bloke. So the take-away is this: in Lua, ordering matters (which should have been apparent because it is interpreted, not compiled). I re-ordered my functions and I was able to make all of the ones I wanted as local functions to be local.