[英]Lua: strange behavior with loadstring?
我在Lua 5.1中使用loadstring
:
主要
function Object:load_string(str)
loadstring(str)() -- self in this is 'nil'
print(self) -- self here is a 'table'
end
obj:load_string('print(self)')
产量
> nil
> table: 1557C890
为什么该self
中使用loadstring
解析为一个nil
值时, self
变量是在该函数访问并且可以直接打印?
字符串(或文件)中包含的代码与当前作用域没有任何关系。 loadstring()
创建新的匿名vararg函数。 您必须明确地传递self
。
function Object:load_string(str)
loadstring(str)(self) -- pass self explicitly
print(self) -- self here is a 'table'
end
obj:load_string('local self = ...; print(self)')
str
中的代码很可能包含对self
作为全局变量的引用。 在self
中load_string
是一个局部变量,在代码无法访问str
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.