Page 2 of 2

Re: Indexing strings in Lua?

Posted: Mon Mar 21, 2011 12:18 pm
by crow
Hey I can see what the rest is doing but what is this one doing ?

Code: Select all

function smt.__index(str, key)
  if type(key) == 'number' then
    return string.sub(str, key, key)
  elseif stringMethods[key] then
    return stringMethods[key]
  end
end

Re: Indexing strings in Lua?

Posted: Mon Mar 21, 2011 1:28 pm
by vrld
BlackBulletIV wrote:You might want to just make the __index function look at the string library, so can call all string functions from a string itself.
That's already possible...

Code: Select all

local str = 'foo bar baz'
for i in str:match("%w+") do -- same as for i in string.match(str, "%w+")
    print(i, i:sub(1,1))
end

print(("pi = %.5f"):format(math.pi)) -- shorthand for string.format("pi = %.5f", math.pi)
If you really want str:print(), you can do it like so (no need to get the metatable):

Code: Select all

function string.print(str, ...)
    print(str, ...)
end
You can even make shortcuts to often used functions (although it can make your code way harder to read):

Code: Select all

string._ =  string.format
print( ("pi = %.f5"):_(math.pi) )

Re: Indexing strings in Lua?

Posted: Mon Mar 21, 2011 8:15 pm
by BlackBulletIV
crow wrote:Hey I can see what the rest is doing but what is this one doing ?

Code: Select all

function smt.__index(str, key)
  if type(key) == 'number' then
    return string.sub(str, key, key)
  elseif stringMethods[key] then
    return stringMethods[key]
  end
end
If the key is a number, it'll get that character. If the key is a member of the stringMethods table, it'll return that.

As for your post vrld, I didn't know that the full string library was indexed. I thought I remember getting an error when I tried one of the functions, but, I obviously didn't.

As for ('f'):print(), I couldn't be stuffed with that, it's actually more characters and I would assume it performs worse.

Re: Indexing strings in Lua?

Posted: Mon Mar 21, 2011 8:54 pm
by Robin
BlackBulletIV wrote:As for ('f'):print(), I couldn't be stuffed with that, it's actually more characters and I would assume it performs worse.
What could be nice:

Code: Select all

function string:print()
    print(self)
    return self
end

do(something(with(strings:print()):print()):print()):print()
Might be useful for debugging.

Re: Indexing strings in Lua?

Posted: Tue Mar 22, 2011 6:25 am
by BlackBulletIV
Hey that's cool, largely for debugging.