I’m trying to structure some of my code so that it follows similar lines to the APIs made available already (ie i2c.configure(), i2c.write etc). I’m not sure whether this is implemented as a class (that is never instantiated) or a table of functions and properties. I’m curious to know why Squirrel treats the following code they way it does:
`class Test1 {
function configure(startValue){ index <- startValue; }
function increment(){ index <- index+1; }
function update(newValue){ index <- newValue; }
}
Test2 <- {
function configure(startValue){ index <- startValue; }
function increment(){ index++; }
function update(newValue){ index = newValue; }
}
class Test3 {
function configure(startValue){ index <- startValue; }
function increment(){ index++; }
function update(newValue){ index = newValue; }
}
Test1.configure(22);
server.log("Test1 is "+Test1.index);
Test1.increment();
server.log("Test1 is "+Test1.index);
Test1.update(33);
server.log("Test1 is "+Test1.index);
Test2.configure(44);
server.log("Test2 is "+Test2.index);
Test2.increment();
server.log("Test2 is "+Test2.index);
Test2.update(55);
server.log("Test2 is "+Test2.index);
Test3.configure(66);
server.log("Test3 is "+Test3.index);
Test3.increment();
server.log("Test3 is "+Test3.index);
Test3.update(77);
server.log("Test3 is "+Test3.index);
`
I want the property index to be persistent and indeed it is for the Test1 and Test2. It fails for Test3 with “trying to set ‘class’”.
The output is as follows:
[Device] Test1 is 22 [Device] Test1 is 23 [Device] Test1 is 33 [Device] Test2 is 44 [Device] Test2 is 45 [Device] Test2 is 55 [Device] Test3 is 66 [Device] ERROR: trying to set 'class' [Device] ERROR: at increment:20
Why does the class Test1 work and Test3 fail?
In general, if I’m trying to encapsulate functionality into a handy object that I can reuse across projects and easily drop in or pull out, should I simply implement it as a table (as in Test2)?