table of Contents
Lua environment example description
Load function that allows parameter passing
位于如下包体封装好的load函数 (等同于直接在Lua环境执行的loadstring函数)
load(chunk, chunkname, mode, env)
Lua environment example description
a = 100
local content = [[
return a
]]
local func = loadstring(content)
print(func())
Equivalent to
a = 100
local func = function()
return a
end
print(func())
If the error is reported as bad argument #1 to'loadstring' ..., just change the loadstring to load (similarly, if the load function reports an error, then change to loadstring) This may be caused by different lua libraries used in different environments, directly Using the editor to run Lua code is to use the loadstring function, otherwise it may be the load function. The error is as follows:
lua.exe AA.lua
lua.exe: AA.lua:9: bad argument #1 to 'load' (function expected, got string)
stack traceback:
[C]: in function 'load'
AA.lua:9: in function 'AFunc'
AA.lua:14: in main chunk
[C]: ?
Load function that allows parameter passing
local A = {}
function A:AFunc()
local content = [[
return function(self)
return self.id > 100
end
]]
self.id = 1000
local loadFunc = load(content) --load返回的是一个无参匿名方法
local myFunc = loadFunc() --执行load返回的方法,拿到content字符串里写的有参匿名方法
local boolValue = myFunc(self) --执行有参匿名方法,传递self进去,返回boolean值(true)
print(boolValue)
end
A:AFunc()
Equivalent to
local A = {}
function A:AFunc()
self.id = 1000
local loadFunc = function()
return function(self)
return self.id > 100
end
end
local myFunc = loadFunc()
local boolValue = myFunc(self)
print(boolValue)
end
A:AFunc()
That is, load(content) is equivalent to function() content end (currently I find that I can’t pass any parameters to this function(), but it can be achieved through my example of passing parameters above)
Note: content is a string including [[]], and the special characters in it are invalid. If content does not write return, an error will be reported!