Order indifferent local functions for cleaner code

A topic for the feature request for a discussion.

AFAIK this is a Lua thing not Defold.

1 Like

Agree with @selimanac. Would have to modify how Lua interpreter works, so I think this request is wishful thinking.

…but I also would like this to be added. :sweat_smile:

I figured this is a Lua thing. There must be ways to achieve this as the script files are controlled by the engine, the question would be at what cost… I think that it will be totally worth it as it should ease the development process and improve code readability.

Maybe it is possible for script files parsed by sdk. But I believe it require a lots of work and not even sure if it is necessary.
It is just how Lua works, functions are just variables in Lua.

What does it mean for functions to be “first-class values”? It means that, in Lua, a function is a value with the same rights as conventional values like numbers and strings.

https://www.lua.org/pil/6.html

2 Likes

I do think there are a lot of benefits. Not only it helps to organize the code better and make it cleaner, but it also helps to eliminate runtime errors when one accidentally places local functions incorrectly.

This seems doable. Even Editor extensions can read and modify project script files.


At this point I’m wondering are any major drawbacks in the workaround that I showed on Github (read below Option A and Option B).

Are here any Lua experts that can explain the difference between the following two approaches? Will Option B consume more memory because of closures, or will run noticeably slower? Or anything like that?

Option A

image
…
image

Option B


…
image

@mikatuo I wrote this in your feature request but thought I should replicate it here:

Thank you for a very well written feature request.

The problem you are describing is a problem with Lua, not with Defold. We use the LuaJIT or Lua 5.1.5 and both of these and the language itself actually care about the order in which functions are defined, or rather the order of variable definitions. We will not do anything on our end to address this as we do not consider it a problem which we can or should solve.

2 Likes

The difference is at what time during execution that the functions will be assigned to the variables:

-- these two are equivalent
-- on the next line of execution there will be a local
-- variable named foo that is assigned the function
local function foo() print("foo") end
local foo = function() print("foo") end

-- but this is obviously different

-- declare local foo with value nil
local foo

-- do something else
for i=1,100000 do
-- no-op, foo is still nil
end

-- assign foo with the anonymous function
foo = function() print("foo") end

-- now we can use foo
foo()

Thank you! Appreciate the explanation.