[Snek] How to return a string from builtin?
keithp at keithp.com
Wed Feb 19 11:37:04 PST 2020
"Mikhail Gusarov" <dottedmag at dottedmag.net> writes:
> How do I return a string from a builtin?
> I've got it working in the following way, but it seems suboptimal:
> size_t len = strlen(s);
> char *new = snek_alloc(len + 1);
> if (new)
> memcpy(new, s, len);
> return snek_string_to_poly(new);
That looks correct. Note that snek_alloc always clears memory, so the
trailing null will already be there. It *might* be better to copy that
explicitly so that future readers won't have to remember that.
> — `s` here is always one of 8 constants, so I can allocate 8 strings
> at the start and return one of them, but maybe there is a way to
> completely avoid allocations?
You have to allocate space in the Snek heap or you won't be able to
reference them. But, yes, you could allocate them at startup time (or
even on first use). To do this, you'll have to reference them during
garbage collection or they'll get dropped.
You might consider using numeric values instead of strings and adding
builtin variables with the desired name?
Another option is to make them built-in variables with a string
value. There's already support for creating builtin values at startup
time which is used by the snekboard and crickit ports to make lists
containing two values. Adding support for creating strings would be
easy to do.
The syntax in the .builtin file looks like this:
M1, -2, = snek_list_build(snek_list_tuple, 2, snek_float_to_poly(8), snek_float_to_poly(9))
We could create a 'snek_string_build' function that took a constant
string and created a snek string, then you could create constants like:
foo, -2, = snek_string_build("foo")
We'd need some function to return the value of that global, which does
run the risk of having the user smash the global with some other
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 832 bytes
Desc: not available
More information about the Snek