Search code examples
variablesluanullcomputercraft

Lua - Computercraft - attempt to call nil, but works sometimes..?


Everytime this program startup , the program runs after a server restart this error shows up:

startup:13: attempt to call nil

When i comment out that line of code the same happens to the line after that, and after that.

Until all those four lines are. (the round(math.floor) lines) Then the program starts.

The four variables is needed in the program so it wont run well with them commented out.

If i now uncomment those lines the program starts perfectly and everything works.

Any reason what im doing wrong?


Solution

  • Functions must be defined before they are called (round is defined on line 72, but called on line 5). You can declare a function prior to defining it:

    function program()
        local round -- forward declaration
        while true do
    
            -- call function defined below
            turbEnergy = round(math.floor(turbine.getEnergyStored())/100000,1) 
    
            -- function definition
            function round(val, decimal)                
            end