Getting an error with variable not existing in a class

I cant work out what I’m doing wrong. Here is the short log:

2023-04-23T09:51:23.999 +00:00 	[Status] 	Agent restarted: reload.
2023-04-23T09:51:24.021 +00:00 	[Agent] 	constructor
2023-04-23T09:51:24.021 +00:00 	[Agent] 	done
2023-04-23T09:51:29.010 +00:00 	[Agent] 	(function : 0x7fe00edd2840)
2023-04-23T09:51:29.010 +00:00 	[Agent] 	i:0
2023-04-23T09:51:29.010 +00:00 	[Agent] 	in add(), ttl: 5
2023-04-23T09:51:29.117 +00:00 	[Agent] 	ERROR: the index 'i' does not exist
2023-04-23T09:51:29.117 +00:00 	[Agent] 	ERROR:   in add agent_code:26

Which is created with this code:

class ThingClass
{
    a = null;
    b = null;
    ttl = null;
    i = null;
    callback = null;
    
    constructor(ma, mb)
    {
        a = ma;
        b = mb;
        ttl = 0.0;
        i = 0;
        server.log("constructor");
    }
    
    function done()
    {
        server.log("in done(), ttl: " + ttl);
        callback(ttl);
    }
    
    function add()
    {
        server.log("i:" + i)     <<<< line 26 where error occurs
        if (i < 5) {
            imp.wakeup(0.1, add);
            ttl = ttl + a + b;
            i++;
            server.log("in add(), ttl: " + ttl);
        } else {
            server.log(i);
            ttl = ttl / i;
            done();
        }
    }
    
    function read(cb)
    {
        callback = cb;
        server.log(cb);
        add();
    }
}

function cback(result) {
    server.log(result);
}

local tc = ThingClass(2,3);

imp.wakeup(5, function() {
    tc.read(cback);
});

server.log("done");

Any help appreciated.

H

You need to bind the context of the class instance to your reference to the add method when you use imp.wakeup
E.g. imp.wakeup(n, add.bindenv(this))