self in loadstring (ANSWERED)

I take it any expression given to “loadstring” can’t contain “self” because the expression gets evaluated in the global environment where self doesn’t exist. True or false?

No one knows the answer?

You can use self if they are in a function like :


a = class()

function a:touched(touch)
   -- you can use self
end

And if you want use the “current” self, stock in global just before :



this = self
assert(loadstring(data))()


@starblue generally you are correct, you cannot put self into loadstring without providing a reference to the “self” variable. However considering the “instance” call class:func() is just a short cut or “sugar” for calling class.func(self) and passing through “class” in the self local variable, consider the following example :slight_smile:

ClassTest = class()

function ClassTest:init(x)
    -- you can accept and set parameters here
    self.x = x
    
end

function ClassTest:test()
    loadstring("return function(self) print(self.x) end")()(self)
end

test = ClassTest("testclass")
test:test() -- prints 'testclass'

That’s useful, thanks.