侧边栏壁纸
博主头像
丛庆

没事儿写代码,有事写代码。email:1024@cong.zone

  • 累计撰写 116 篇文章
  • 累计创建 97 个标签
  • 累计收到 4 条评论
lua

【Lua】require多文件调用

丛庆
2023-12-24 / 0 评论 / 0 点赞 / 115 阅读 / 298 字 / 正在检测是否收录...
温馨提示:
部分资料和图片来源于网络,如有危害到您的利益请与我联系删除,1024@cong.zone。

同级目录文件调用

新建一个名为hello.lua的文件
再新建一个名为main.lua的文件

hello.lua文件中的内容

print("hello lua")

image-1703361487420

main.lua文件中的内容

require("hello.lua")

image-1703361503117

执行main.lua
image-1703361530221

多级目录调用

main.lua所在目录新建一个hello目录,在hello目录中新建一个hello2.lua文件

print("hello hello lua")

image-1703361906846
main.lua文件中requirehello2.lua

require"hello.hello2"

image-1703361954870

执行main.lua
image-1703362020675

多次require同一个文件只会运行一次

把path加入package.path

将目录加入package.path在require的时候就不需要再写路径了

package.path = package.path..";./hello/?.lua"
require"hello2"

image-1703362369354
执行main.lua
image-1703362382600

文件可以return

./hello/hello2.lua文件末尾增加return

print("hello hello lua")

return "hello"

image-1703362566156

main.lua中引入hello2.lua获取返回值

package.path = package.path..";./hello/?.lua"
local res = require"hello2"
print(res)

执行main.lua

image-1703362666270

调用其他文件的函数

hello.lua文件中创建一个tabletable中创建一个函数元素,returntable

local htable = {}

function htable.say()
    print("say hello")
end

return htable

image-1703362986811

main.lua中引用hello.lua

hello = require("hello")

hello.say()

image-1703363027476

执行结果
image-1703363037359

0

评论区