lua中使用"/"或"."的require路径有什么不同?

我看到一些lua代码使用两种方式来指定require路径。 例如:

require("a/b/c")
或
require("a.b.c")

我想知道以上两种方式的不同点。并且我们能在同一个程序中同时使用这两种方式吗?

点赞
用户11740758
用户11740758

将下面翻译成中文并且保留原本的 markdown 格式

简单的方法是在 Lua 控制台 lua -i 中执行操作-...

>lua -i
Lua 5.3.5  Copyright (C) 1994-2018 Lua.org, PUC-Rio
> require("a/b/c")
stdin:1: module 'a/b/c' not found:
    no field package.preload['a/b/c']
    no file '/usr/local/share/lua/5.3/a/b/c.lua'
    no file '/usr/local/share/lua/5.3/a/b/c/init.lua'
    no file '/usr/local/lib/lua/5.3/a/b/c.lua'
    no file '/usr/local/lib/lua/5.3/a/b/c/init.lua'
    no file './a/b/c.lua'
    no file './a/b/c/init.lua'
    no file '/usr/local/lib/lua/5.3/a/b/c.so'
    no file '/usr/local/lib/lua/5.3/loadall.so'
    no file './a/b/c.so'
stack traceback:
    [C]: in function 'require'
    stdin:1: in main chunk
    [C]: in ?
> require("a.b.c")
stdin:1: module 'a.b.c' not found:
    no field package.preload['a.b.c']
    no file '/usr/local/share/lua/5.3/a/b/c.lua'
    no file '/usr/local/share/lua/5.3/a/b/c/init.lua'
    no file '/usr/local/lib/lua/5.3/a/b/c.lua'
    no file '/usr/local/lib/lua/5.3/a/b/c/init.lua'
    no file './a/b/c.lua'
    no file './a/b/c/init.lua'
    no file '/usr/local/lib/lua/5.3/a/b/c.so'
    no file '/usr/local/lib/lua/5.3/loadall.so'
    no file './a/b/c.so'
    no file '/usr/local/lib/lua/5.3/a.so'
    no file '/usr/local/lib/lua/5.3/loadall.so'
    no file './a.so'
stack traceback:
    [C]: in function 'require'
    stdin:1: in main chunk
    [C]: in ?
>

请注意,这个输出出现了 a.b.c 但没有 a/b/c

    no file '/usr/local/lib/lua/5.3/a.so'
    no file '/usr/local/lib/lua/5.3/loadall.so'
    no file './a.so'

...这个回答了你的问题吗?

试试这个...

>lua -i
Lua 5.3.5  Copyright (C) 1994-2018 Lua.org, PUC-Rio
> dump=function(dump) for key,value in pairs(dump) do io.write(string.format("%s = %s\n",key,value)) end
>> end
> dump(package.preload)
> package.preload["a.b.c"]=function() return "WHATSUP" end
> dump(package.loaded)
package = table: 0x56614f00
io = table: 0x56615860
math = table: 0x56616ce0
os = table: 0x56615f40
coroutine = table: 0x566153a0
bit32 = table: 0x56618730
debug = table: 0x56618350
utf8 = table: 0x56617880
string = table: 0x566166b0
_G = table: 0x566136d0
table = table: 0x56615640
> require("a.b.c")
WHATSUP
> dump(package.loaded)
package = table: 0x56614f00
io = table: 0x56615860
math = table: 0x56616ce0
os = table: 0x56615f40
coroutine = table: 0x566153a0
a.b.c = WHATSUP
bit32 = table: 0x56618730
debug = table: 0x56618350
utf8 = table: 0x56617880
string = table: 0x566166b0
_G = table: 0x566136d0
table = table: 0x56615640
> ;-)
2020-12-06 13:20:59