Lua-基础(六)加载使用其他Lua的函数

Lua-基础(六)加载使用其他Lua的函数
fastylua的特点之一就是方便的调用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
和load类似的还有loadfile,但loadfile加载的是文件而非字符串。
我们在funTest.lua文件中写一句输出:print('Test')
然后在其他文件中调用:
local fun=loadfile('funTest.lua',"t")
fun()
通过这种形式我们就可以吧funTest.lua的内容当做一个函数来使用,以上使用后会输出Test。
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('你好')
说明
使用表加载和非表加载都可以实现效果,使用表加载时,有点面向对象的感觉可能更方便。
评论
匿名评论隐私政策





