开发者

Lua scoping question regarding modules/require

开发者 https://www.devze.com 2023-02-11 02:20 出处:网络
I\'m using quasi the module approach开发者_开发百科 \"From a Table - Using Locals Internally\" as described on this page.

I'm using quasi the module approach开发者_开发百科 "From a Table - Using Locals Internally" as described on this page.

local M = {}

-- private
local x = 1
local function baz() print 'test' end

local function foo() print("foo", x) end
M.foo = foo

local function bar()
  foo()
  baz()
  print "bar"
end
M.bar = bar

return M

However, I don't add functions etc. to the module table after the definition of the function. Instead I do it at the bottom of the file.

local x = 1
local function baz() print 'test' end

local function foo() print("foo", x) end

local function bar()
  foo()
  baz()
  print "bar"
end

local M = {
  bar = bar,
  foo = foo,
}
return M

As can clearly be seen M is a local variable. I wondered if a change to

local x = 1
local function baz() print 'test' end

local function foo() print("foo", x) end

local function bar()
  foo()
  baz()
  print "bar"
end

return {
  bar = bar,
  foo = foo,
}

is equivalent. I suppose the returned table is global but afaik if I'd use this module in another like

local foo = require 'foomodule'

it would not make a difference (performancewise) because I bind the local variable foo to the returned table.


Short version: All those snippets of code are equivalent.

Apparently the creation of a global module table is up to the user writing a module. require"foomodule" correctly loads the module, but it does not create the foomoduletable in the globals table _G. It does create a module table in package.loaded.

So basically it's your choice:

  1. Generate the global module table in your module, and just require "foomodule" will create the global foomodule table
  2. Leave the decision up to the user: do as in the third code snippet, and just return an unnamed table.

In my opinion, option 2 is to preferred as it doesn't accidentally ruin a users table which has the same name as your module, or at least he'll know he's erasing his table if he sees foo = require'...'. However it seems most modules use the first approach, and just hope this problem does not occur.

As for the locals, it's simple, a local is a local ;). So if you declare a local it's only available in the scope it is declared in (see section 2.6: Visibility in the Reference Manual).

0

精彩评论

暂无评论...
验证码 换一张
取 消