I am using loadstring
with Lua 5.1:
Main
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)')
Output
> nil
> table: 1557C890
Why is it that the self
used in loadstring
resolves to a nil
value when the self
variable is accessible in the function and can be printed directly?
Code contained in string (or file) is not related to current scope in any way. loadstring()
creates new anonymous vararg function. You must pass self
explicitly.
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)')
Most probably, the code in str
contains a reference to self
as a global variable . The self
in load_string
is a local variable, not accessible to the code in str
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.