Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global function in lua

Is there a way to have a function in Lua that can be accessed from any module in a project without having to first require it?

something like:

module(..., package.seeall);
function globFoo()
       print('global foo called');
end

and have it called from somwhere else, like main

--main

globFoo();

without requiring it?

like image 491
ZachLHelms Avatar asked Dec 27 '22 19:12

ZachLHelms


2 Answers

A module is just a Lua script. You can do whatever you want there; you don't even have to call module in your module script. Indeed, module is generally considered harmful these days, which is why it was deprecated in Lua 5.2.

Really, it's a matter of simply moving your code around:

function globFoo()
       print('global foo called');
end
module(..., package.seeall); --Module created after global function

So yes, you can have a module modify the global table. I would very much suggest that you don't (because it creates implicit ordering between Lua scripts, which makes it hard to know which script uses which stuff). But you can do it.

like image 119
Nicol Bolas Avatar answered Jan 04 '23 03:01

Nicol Bolas


A sample of how this is done :

in global.lua (where the global function is located) :

globalFunction1 = function(params)
    print("I am globalFunction1")
end

In the calling file, caller.lua :

globalFunction1(params)    -- This will call the global function above
like image 39
Britc Avatar answered Jan 04 '23 02:01

Britc