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

Attempt to call nil.... executing a function in the same table

Started by Goof, 17 February 2014 - 07:00 AM
Goof #1
Posted 17 February 2014 - 08:00 AM
Hello.

I have no idea if this've been asked before, but i am having trouble executing a function from a function inside the same table…


what is happening:
Spoiler

menu = {
function_one=(
function()

end
)

function_two=(

function()
menu.function_one() -- this is returning attempt to call nil..... why?
function_one() -- i also tried with this, but the same error....


end
)



}



my table code
Note that im having different functions all around my full code etc.. ( like a button function )


Spoiler


local menu={
  settings=(
    function()



    end
  );
	start=(
		function()
      activeWindow={
        xmin=1,xmax=screen[1]/2-screen[1]/2/2/2,ymin=6,ymax=18
      }
      for i = 18,6,-1 do
        paintutils.drawLine(
          1,
          i,
          screen[1]/2-screen[1]/2/2/2,
          i,
          colors.gray,
          colors.white
        )
      end
      setButton(
        "Settings",
        settings, -- this is the function which should be executed
        1,
        screen[1]/2-screen[1]/2/2/2,
        6,
        8,
        colors.black,
        colors.yellow,
        colors.red,
        false
      )
      Buttonscreen()
		end
	);

}

Do i really have to seperate these functions into stand-alone functions instead of having them in one table?


Thanks in Advance


Edit…. 555'th post xD
Edited on 17 February 2014 - 07:15 AM
LBPHacker #2
Posted 17 February 2014 - 08:36 AM
local menu
menu = { -- ...
So Lua will know what menu is when you declare the function that indexes it.
Edited on 17 February 2014 - 07:37 AM
theoriginalbit #3
Posted 17 February 2014 - 08:37 AM
the problem is that when the table is defined those variables do not exist within its scope, so it will search for them in the global scope, one way (other than LBPHacker's method) to circumvent this is by doing the following.


local menu = {}
menu.draw = function()
  --# do note that draw cannot call onClick, you have to use some forward declarations to do that
end
menu.onClick = function()
  --# onClick can invoke draw
end
Edited on 17 February 2014 - 07:37 AM
LBPHacker #4
Posted 17 February 2014 - 08:45 AM
draw cannot call onClick, you have to use some forward declarations to do that
That's not entirely true. If draw calls onClick by calling the function held by menu.onClick, that's fine. That only requires menu to be declared earlier. Although, when you have two local functions, you really have to forward declare one of them:
local a
local b = function(invoke) if invoke then return a(false) end end
a = function(invoke) if invoke then return b(false) end end
Goof #5
Posted 17 February 2014 - 09:33 AM
Ohh Well that explained a lot why it didn't work… xD


Thanks for your help