Function got replaced by child game object's function (SOLVED)

So we’ve got the following main collection:

outline

good.script:

function init(self)
	print("good.script init")
	do_good(self)
end

function do_good(self)
	print("Good")
end

bad.script:

function init(self)
	print("bad.script init")
	do_good(self)
end

function do_good(self)
	print("BAD!")
end

And when you run the game:

DEBUG:SCRIPT: good.script init
DEBUG:SCRIPT: BAD!
DEBUG:SCRIPT: bad.script init
DEBUG:SCRIPT: BAD!

It seems to me that standard game object functions (init, final, update, etc) got it’s own namespace but user functions (do_good in this case) are in global namespace.

1 Like

Now you are using global functions and in your case it is shadowing of function.

If you want to use local function you have to write:

local function do_good(self)
...

and local function have to be above it’s calling

1 Like

You can also forward declare the function:

local my_func

function init(self)
    my_func()
end

my_func = function()
    ...
end
2 Likes

I see this is the problem of Lua by default puts variables in global, like JavaScript. Although I’d be more happy if game object functions (init, final, update, etc) are also shadowed, at least they behave (fail) consistently :grinning:

So I guess this won’t be “fixed”?

Thanks for reminding me the use of local.

1 Like

Thanks for pointing that out

You can use superstrict force yourself to use only local functions or functions that you have explicitly said should be global.

As I think it shouldn’t be fixed. It is “how to” LUA works.

This is https://www.defold.com/manuals/lua/ intro to LUA with Defold, and there is links to other materials.
More links you can find here: Big List of Lua Resources!

1 Like

I’m hoping that the new code editor that @mats.gisselson is working on will allow us to easily integrate a linter such as LuaCheck. LuaCheck would have caught this problem.

2 Likes

Thanks, but it’s too much of trouble for little gain for me, since the whitelist can grow, unless I can just do require("defold.strict").

Understood, although I wish Lua forced us to either declare global or local without default. It seems to me Lua developers are OK with global-by-default, I just have to blend in and suck it up then.

1 Like

That would be a proper fix!

1 Like