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

[Lua][Error]Attempt to call nil

Started by Greyhat, 27 December 2012 - 01:32 PM
Greyhat #1
Posted 27 December 2012 - 02:32 PM
I'm working on a program that will mine in a pinwheel pattern, while gathering all of the ores it finds. It always errs on the first call that I make to one of my own functions. I get "Pinwheel :28: attempt to call nil".

I have tried moving my calls such that they come after the function they call is read, but with the current structure of my code it is not possible to do that for the entire program.

I have also tried relegating 4 lines under "–Here be the main" to a Main() function, and then calling that function only at the very end, but had no luck there either.

http://pastebin.com/5wprJJjh

Thank you for your time!

*edit for clarity

** Edit 2: Got it past the compiler by removing "local" from all of my functions and moving he 4 lines under "–Here be the main" to the end of the program. I'm still experiencing all sorts of oddness, but I'm troubleshooting that. Still, any inputs on the code would be appreciated!
ChunLing #2
Posted 27 December 2012 - 03:30 PM
You can declare a variable/identifier and then assign/define it later. So even if you need to use a function in a function that (for some reason, and I've encountered a few) needs to be defined before the function it uses, you can do this:
local neededFunction
local function usingFunction()
  neededFunction()
end  --defined, but we can't use it yet
neededFunction = function()
  --some code
end
usingFunction() -- now we can call this
Global functions avoid this (very minor) difficulty with identifier scope, but they do not at all prevent you from needing to assign/define a non-nil value for a variable before you actually use/call it.

The actually is important, because in the above example we use a call to neededFunction in our definition of usingFunction, but we aren't actually calling/using neededFunction until after we define it ().

You should post your current code and your current errors, if you want help with those.
Greyhat #3
Posted 27 December 2012 - 05:01 PM
You should post your current code and your current errors, if you want help with those.

I'd like to beat my head against them for a while before I bring them here. If I get stuck on something though, I certainly will :)/>. Thank you very much for your help.