[英]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.