[Snek] How to return a string from builtin?
keithp at keithp.com
Wed Feb 19 12:29:47 PST 2020
"Mikhail Gusarov" <dottedmag at dottedmag.net> writes:
> These are names of colors: "none" / "red" / "black" / ....
> I don't have an opinion whether numbers or strings are better here —
> what do you think?
Hrm. I think you're string value idea is better than my number
idea. Strings are easier to read when you just print the sensor value,
and that's definitely a feature for the user.
Let's figure out how to make that work. I think it's going to require
some changes to the snek core, which is always fun.
I think there are (at least) three approaches:
1) Allocate a new string at each return. You've already got that
2) Define builtin variables referencing the strings. The mechanism for
setting up the variables and pointing them at the strings is already
in place; a helper 'snek_string_build' would make this slightly
easier. These variables will be writable by the user, so a mistake
could easily cause confusion.
3. Allocate strings without variables, either on the fly or at startup. This
requires teaching the garbage collector about your strings.
Reading through the code, it looks like the snek value stack could
very easily hold references to your strings, and you could fetch
values directly from there.
We would make a tiny change to snek_exec to reset the stack pointer
to the value when snek_exec was called rather than zero. Then you
would use snek_stack_push_string at startup time, saving the
stack pointer for the first string and using
snek_stack[saved_value + offset] to fetch strings for return.
> Also I suppose I should return None instead of "none" here if sensor
> doesn't detect any color.
Oh, that's a good idea -- that way it's usable as a boolean.
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 832 bytes
Desc: not available
More information about the Snek