Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

local and global functions
Started by DevilDev May 10 2018 06:58 PM

2 replies to this topic

Best Answer roaminggamer , 10 May 2018 - 07:30 PM

Use forward declaration instead of globals to solve scope issues:

local a
local b
local go

a = function(num)
   go(num)
end

b = function(num)
   go(num)
end

go = function( num )
   print("zzzz", num )
end

a(1)
b(2)
go(3)

Regardless, you cannot call a function till it has been defined.

So, this would be wrong:



local a
local b
local go

a = function(num)
   go(num)
end

b()

b = function(num)
   go(num)
end

go = function( num )
   print("zzzz", num )
end

[TOPIC CONTROLS]
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

DevilDev

[GLOBAL: userInfoPane.html]
DevilDev
  • Enthusiast

  • 51 posts
  • Corona SDK

A local function is able to access a global function but another function is not.Why?

local function a()
	go()
end
a()

local function b()
	go()
end

local something=dis....
something:addEventListener("tap",b);


function go()
print("zzzz")
end

function "a" produces an error.Function "b" works..But both are same type of functions right??



[TOPIC: post.html]
#2

roaminggamer

[GLOBAL: userInfoPane.html]
roaminggamer
  • Corona Geek

  • 6,920 posts
  • Corona SDK

  Best Answer

Use forward declaration instead of globals to solve scope issues:

local a
local b
local go

a = function(num)
   go(num)
end

b = function(num)
   go(num)
end

go = function( num )
   print("zzzz", num )
end

a(1)
b(2)
go(3)

Regardless, you cannot call a function till it has been defined.

So, this would be wrong:



local a
local b
local go

a = function(num)
   go(num)
end

b()

b = function(num)
   go(num)
end

go = function( num )
   print("zzzz", num )
end

Edited by roaminggamer, 10 May 2018 - 07:31 PM.


[TOPIC: post.html]
#3

roaminggamer

[GLOBAL: userInfoPane.html]
roaminggamer
  • Corona Geek

  • 6,920 posts
  • Corona SDK

This also works thanks to forward declaration:
Use forward declaration instead of globals to solve scope issues:

local a
local b
local go

-- By the time the closures execute a,b, and go have been defined.
timer.performWithDelay( 100, function() a(1) end )
timer.performWithDelay( 100, function() b(2) end )
timer.performWithDelay( 100, function() go(3) end )

a = function(num)
   go(num)
end

b = function(num)
   go(num)
end

go = function( num )
   print("zzzz", num )
end



[topic_controls]
[/topic_controls]