Could someone explain the difference between the two ways I’ve seen of defining functions within a module? Namely:
function blah()
end
and
blah = function()
end
Barry [import]uid: 46639 topic_id: 9410 reply_id: 309410[/import]
Could someone explain the difference between the two ways I’ve seen of defining functions within a module? Namely:
function blah()
end
and
blah = function()
end
Barry [import]uid: 46639 topic_id: 9410 reply_id: 309410[/import]
They are essentially the same thing. [import]uid: 7563 topic_id: 9410 reply_id: 34478[/import]
Sure essentially, but is there even a minor difference (speed, cpu, ram usage etc)?
Might as well go with which-ever is best right from the start
Barry [import]uid: 46639 topic_id: 9410 reply_id: 34482[/import]
Reading LUA book right now… It seems following is tinybit better
blah = function()
end
As per my understanding function blah() … end is translated to blah = function () … end at compilation…
I may be wrong tho… [import]uid: 48521 topic_id: 9410 reply_id: 34484[/import]
The difference is merely stylistic.
Both have to be compiled into byte code. Any difference in speed will be minute. Even if you could measure the difference in speed, it is an implementation detail which could change in the future.
I personally prefer
function foo()
end
but that is probably because I’m biased/brain-damaged from working with other languages that don’t support anonymous functions and functions as first class values.
[import]uid: 7563 topic_id: 9410 reply_id: 34520[/import]
It’s exactly the same as one is just syntactic sugar (function blah) for the other.
There is just one tiny difference if I recall.
With
[lua]blah = function()
end[/lua]
You can’t recursively call blah (the function) as it is not yet assigned to the variable blah. [import]uid: 51516 topic_id: 9410 reply_id: 34525[/import]
I think for simple reading function jellyOnAPlate() wins out, but I did just find an example of when the other way is better:
In my scenes (director homage) code, each transition is a function.
These functions are stored in a transitions table.
I had a choice, either do:
local function RedLorry() … end
transitions.RedLorry = RedLorry
or
transitions.RedLorry = function() … end
So while 99% of the time it doesn’t matter, here it did [import]uid: 46639 topic_id: 9410 reply_id: 34537[/import]
seth is right, until the ‘end’ the var you are assigning the function to isnt assigned [import]uid: 34945 topic_id: 9410 reply_id: 34791[/import]
Ah I missed that post, thanks, very useful. [import]uid: 46639 topic_id: 9410 reply_id: 34827[/import]
Seth is right!! Internally, Lua converts this:
[lua]local function blah()
– some code
blah()
end[/lua]
to this:
[lua]local blah
blah = function()
– same stuff
end[/lua]
so that the memory address is pre-assigned, and recursion is supported [import]uid: 6175 topic_id: 9410 reply_id: 35504[/import]