GradualGames wrote:Just for the heck of it, I'm trying to think if there would be a way to do an "ends with" as well with as little code. I haven't thought of anything yet. One would probably have to use .strat and .strlen(arg) and walk back indices from the end of the string in that case. Aw well can't have everything.
Unless there's more voodoo possible with .sprintf I haven't thought of. C lets you do pointer arithmetic but I don't think ca65 is exposing that type of functionality even though it might be calling sprintf in the C runtime under the hood after forwarding various parameters along...
Challenge accepted. I think this one should work:
Code: Select all
.define string_ends_with(string, ends_with) .xmatch(.sprintf(.sprintf("%%.%ds%%s", (.strlen(ends_with) < .strlen(string)) * (.strlen(string) - .strlen(ends_with))), string, ends_with), string)
It works by stripping off
.strlen(string) - .strlen(ends_with) characters from the end of
string, then appends
ends_with to it, and compares to the original string. Some trickery was needed to avoid putting a negative number in the format string in case
ends_with is longer than
string. (ca65 doesn't short circuit expression evaluation so can't use
.and to safeguard it.)
EDIT: "shorter than" => "longer than"