lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Pavol Severa wrote:
Hello
I am a complete newbie to lua (have some experience with python). The
question is - when I run require("name"), all names from name.lua are
included to the global namespace. Is there any way to put them instead
to a table "name"?  What is the standard way of not polluting the
global namespace?
And what is the use of the function "module"?
Thanks a lot for your patience with my confused quetions
Palo

The "module(modname)" function does exactly it: put all functions in a global table named "modname".

Say you have 3 files: main.lua, file1.lua, file2.lua

~~ file1.lua ~~

function foo(bar)
    print('-->', bar)
end



~~ file2.lua ~~

module 'file2' -- it is not obligatory to use the same name of the file.

-- Note that this function has the same name as the one
-- defined in 'file1.lua'
function foo(baz)
    print('==>', baz)
end



~~ main.lua ~~

-- Just to see that 'foo' don't exist yet
print(foo)             -- nil

-- Load and execute file1.lua
require 'file1'

-- Check if the function is defined now
print(foo)             -- function: 0xDEADBEEF

-- Check if has any 'file1' global table
print(file1)           -- nil

-- Load and execute file2.lua
require 'file2'

-- Check that foo is still the one defined in 'file1'
print(foo)             -- function: 0xDEADBEEF

-- Is there a global table named 'file2'?
print(file2)           -- table: 0xAABBCCDD

-- Does it contain a 'foo' function, too? Is it the
-- same defined in file1.lua or is different?
print(file2.foo)       -- function: 0x012345678

foo('hello')           -- -->	hello
file2.foo('world')     -- ==>	world



A few notes:
- module is defined in Lua-5.1, or in Lua-5.0 using compat.lua
- module don't have to be called with the file's name, but it is very advised to do so - module should be the first function to be called in the file/script/chunk, or will you have unexpected behavior.

--rb