lua的特点之一就是方便的调用chunk(代码块)

通过这种特性,我们可以在 a.lua 中调用 b.lua 的内容,甚至可以从字符串文本中调用 lua 当做函数执行~

load

让我们先来看一下 load 函数的定义:
!{load 函数}(https://i.loli.net/2020/02/04/DYGV2CSWoPcL49v.png)
通过定义我们可以知道 load 函数可以加载文本和二进制类型代码块,来让我们尝试一下:

local f=load('I=I+1')
I=0
f()
print('I='..I)
f()
print('I2='..I)

在这个例子中,我们使用 load 加载了’I=I+1’这一串字符串,并把加载结果存储在 f 中。通过使用f()来调用函数。

loadFile

loadFile
和 load 类似的还有 loadfile,但 loadfile 加载的是文件而非字符串。

我们在 funTest.lua 文件中写一句输出:print(‘Test’)
然后在其他文件中调用:

local fun=loadfile('funTest.lua',"t")
fun()

通过这种形式我们就可以吧 funTest.lua 的内容当做一个函数来使用,以上使用后会输出 Test。

dofile

dofile
dofile 与 loadfile 最大的不同就是,loadfile 只是加载函数,需要我们手动去调用,而 dofile 不但加载函数而且直接调用。

dofile('funTest.lua')

require

require 是包含的意思,与 load 系列不同的是,require 会检查被加载的文件是否已经被加载过,防止重复加载。
另外使用 require 加载可以单独调用加载的文件中的函数,而不是把文件内容当做一个函数来使用,所以 require 加载时比较理想的加载形式。

使用表加载

在 funTest.lua 文件中:

local _M = {}
function _M.test()
    print('hi')
end
function _M.Hi()
    print('hi100')
end
function _M.Say(arg)
    print('hi:'..tostring(arg))
end
return _M

在其他文件中调用:

-- 调用其他文件的函数
local test = require('funTest')
if not test then
    print('错误')
    return
end
test.Hi()
test.test()
test.Say(51)

非表加载

在 funTest.lua 中:

function Ac(j)
    print('100:'..j)
end

在其他文件中:

require("funTest")
Ac('你好')

说明

使用表加载和非表加载都可以实现效果,使用表加载时,有点面向对象的感觉可能更方便。