lua-users home
lua-l archive

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




On Tue, Oct 5, 2010 at 4:05 PM, Mark Hamburg <mark@grubmah.com> wrote:
Better to not muck with environments at all. The following works just fine in Lua 5.1 and 5.2:

local M = { }

function M.exportedFunction1()
-- code
end

function M.exportedFunction2()
-- code
end

local exportedFunction2 = M.exportedFunction2 -- fast local access to the function

local function privateFunction()
-- code
end

function M.exportedFunction3()
privateFunction()
exportedFunction2()
end

return M


I guess that's not so bad, if you just accept to write the prefixes. What's so bad about mucking with environment if you consider the example Steve gave? I don't see any downsides, besides that prefixes make the code a bit more explicit (but also a little bit less readable). Is there a performance issue maybe?

 
If you insist on mucking with the global environment, you can always add:

_G[ ... ] = M

People sometimes prefer to write all of the functions as locals and end with:

return {
exportedFunction1 = exportedFunction1,
exportedFunction2 = exportedFunction2,
exportedFunction3 = exportedFunction3
}

This allows you to see all of the exports in one place but it also requires writing the names twice. If you don't trust your spelling, you can help a bit by wrapping the right-hand sides in asserts (or using a lint that hunts for global reads).


Thanks for the tip. I think I like that approach.

Thijs