繁体   English   中英

Lua:loadstring的异常行为?

[英]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 作为全局变量的引用。 selfload_string是一个局部变量,在代码无法访问str

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM