rzimmerman / kal

A powerful, easy-to-use, and easy-to-read programming language for the future.
http://rzimmerman.github.io/kal
MIT License
394 stars 18 forks source link

String interpolation #100

Closed dijs closed 11 years ago

dijs commented 11 years ago

Could this ever be a thing in Kal?

test = "#{2 + 2}"
# where test would equal "4"

Obviously, it would be great to use variables also...

dijs commented 11 years ago

This is from Douglas Crawford's "Remedial Javascript". I thought I might help.

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};
// Usage:
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));

I thought this was a clean way to approach the problem.

rzimmerman commented 11 years ago

If I'm understanding you correctly, you're looking for string syntax like:

s = "I am #{50+1} years old"

Which is already supported. The supplant thing is not supported right now (kind of like Python's old % operator?), although you could do:

a = cow
n = moo
print "The #{a} says #{n}, #{n}, #{n}!"
rzimmerman commented 11 years ago

Also, it only works with double quoted strings, not single quoted strings (on purpose like CoffeeScript).

dijs commented 11 years ago

Facepalm I had no idea this was already supported...

Is it in your documentation?

rzimmerman commented 11 years ago

Technically yes, but it's just one little line in the readme (I agree it's not obvious at all). I'll add something more substantive.