Adding the tostring() method to blob's in the Squirrel Runtime


I am running some off target unit tests using a build of the squirrel run time I got from their website. I use the blob.tostring() method in my code at one point, and obviously it fails on my machine because that is an extension the EI added.

Can I get a hint on how to modify the squirrel source files so I can have that method locally, preferably with the same (or similar) functionality that the EI squirrel run time uses?

Thank you very much!

Per the docs:

This method copies the target blob’s bytes into a new string of 8-bit character values and then returns it. This is behavior unique to the imp implementation of Squirrel, not a standard behavior of the language.

Using code from here:

function readstr(blob) { if(blob.eos()) return null; // if RW pointer is at the end of the stream return null (blob is empty) local out = ""; for(local n = 0; n<blob.len; n++) { // I'm not sure which how this length is represented, I assume it's in bytes but make sure to check if(!blob.eos()) break; local c = blob.readn('b'); out += c.tochar(); } return out; }

Disclaimer I haven’t tested this but at a quick glance I’m pretty sure it should work.

readstr is not the same at tostring. tostring() returns a string of the entire blob, not just from where the blob pointer sits.

Ah I missed that.,‘b’); at the beginning of the function should fix it, I think.

You don’t need to modify the Squirrel source files; you can modify the “blob” class in Squirrel in your test framework:

blob.tostring <- function() {
    local pos = this.tell();, 'b');
    local s = "";
    for (local n = 0; n<this.len(); n++) {
        s += this.readn('b').tochar();
    }, 'b');
    return s;

// your code here:

b <- blob();

b.writen(0x0a216948, 'i');


This won’t work in Electric Imp device or agent Squirrel, where “blob” isn’t quite a real class, it’s something more memory-efficient instead.


Exactly what I was looking for Peter, thank you. I am just embarrassed I didn’t think to even try that.