If I have a file called test1.lua
function print_hi()
print("hi")
end
and I want to make the function available to another file called test2.lua, I write:
require 'test1'
function print_hi_and_bye()
print_hi()
print('bye')
end
But, now let’s say I have a third function called test3.lua to which I want to expose print_hi_and_bye() but NOT print_hi(). If I require ‘test2’ I will have access to both the print_hi and print_hi_and_bye() functions. How do I get around this and keep the functions of test1 local to test2 so that nothing else uses them by mistake? Is there a way to do this with lua’s loading facilities and not just by refactoring code?
Thanks
You need to make
test1.luafunctions only visible for whom requested it. For this, some changes in filestest1.luaandtest2.luaare needed:test1.lua
test2.lua
The changes are minimal, and now you can use the functions only in the files you request them.
In Lua 5.1, you can use the module function in
test1.luafor convenience.In Lua 5.2, this function is deprecated as it violated the design principles of Lua; instead you should do as shown in the first example.