Robin wrote:
Your string.quoted looks good to me, although I don't know how efficient gsub over "." is.
Yo, I'll change that (with a gsub mapping special chars, and another for the rest of those < 0x20).
Robin wrote:
Two things:
Code: Select all
elseif c == '"' then return '\\"'
You don't need the backslash there, and in other places you don't use it.
I don't get what you mean here: I'm
producing an escaped string (thus backslahes are all escaped in the replacement patterns).
Robin wrote:
More importantly:
Code: Select all
string_mt = getmetatable("")
string_mt.__tostring = string.quoted
I wouldn't do this.
Normally, tostring is the identity function for strings. So
tostring(foo) == foo if
foo is a string. Those two lines break that.
Yo, it's a nice property, but have we the choice. __tostring is launched by a call to tostring, isn't it? So, if I want string to be correct eg in table out put, I must hook tostring. So that eg --provided you have a proper tostring for table notation to your taste--, tostring(t) works fine:
Code: Select all
t = {[true]="true", ['nil']="nil", nltab="\n\t", [1]="1", [9]="9"}
print(t)
--> {true="true", 9="9", 1="1", nltab="\n\t", "nil"="nil"}
-- or
--> {true="true", 9="9", 1="1", nltab="\9\10", "nil"="nil"}
-- but not (!) that:
--[[
{true=true, 9=9, 1=1, nltab=
, nil=nil}
]]
Grrr!!! What the f*$k? How can you debug? I want to string to show correctly. Far more important than tostring(s) == s (when is this useful, anyway, else theoretically?); and it gives another hugely useful (according ti me) property:
programmer --> notation -----> Lua --> tostring of s -------> notation --> programmer
With notations equal on both sides as far as possible (with funcs, threads, userdata, let's wait for next Xmas).
[/code]