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

Call a function before its defined

Started by HPWebcamAble, 25 August 2015 - 04:50 PM
HPWebcamAble #1
Posted 25 August 2015 - 06:50 PM
I DON'T mean this:

test()

function test()
  print("test")
end



I mean something more like this:
(The code in question uses my Screen API

local function buttonAction()
  --# Other stuff
  calcSize()  --# Need to call 'calcSize'
end

local function calcSize()
  addButton( "Button1" , buttonAction )  --# Need to pass the 'buttonAction' function
end
This isn't how it actually looks, but this is the general idea.

Assume 'buttonAction' is also called further down in the code by something else


So how would I go about doing this?
Edited on 25 August 2015 - 04:50 PM
Lignum #2
Posted 25 August 2015 - 06:57 PM
Forward declare the function.


local calcSize = nil

local function buttonAction()
   calcSize()
end

calcSize = function()
   addButton("Button1", buttonAction)
end

Though you still have to make sure that calcSize is defined before buttonAction is called.
HPWebcamAble #3
Posted 25 August 2015 - 07:06 PM
Forward declare the function.

Awesome, it works, thanks :)/>
Bomb Bloke #4
Posted 26 August 2015 - 12:53 AM
Note that the "= nil" business is optional. Just "local calcSize" will suffice.