lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,

Using Lua 5.1 (work6).

Is the string's metatable here to stay? Can I confidently convert from 'string.len( aString )' to 'aString:len()' syntax?

If the string's metatable is a permanent feature, what is the recommended way to add new functions to it?

For illustration purpose, lets assume I have a 'startsWith' method which returns true or false if a given string starts with a given prefix:

local StartsWith = function( self, aPrefix )
        if aPrefix ~= nil then
if aPrefix == string.sub( self, 1, string.len( aPrefix ) ) then
                        return true
                end
        end

        return false
end

How do I hook that up with the string's metatable?

Should I directly add it to the metatable __index?

local aString = "Content-Type"
local aMetaIndex = getmetatable( aString ).__index

aMetaIndex.startsWith = StartsWith

print( aString:startsWith( "Content" ) )

> true

Alternatives?

Finally, should the metatable be available to string literals?

"aString":lower()

lua: TestString.lua:106: attempt to call a nil value
stack traceback:
        TestString.lua:106: in main chunk
        [C]: ?

print( "aString":lower() )

lua: TestString.lua:106: ')' expected near ':'

TIA!

Cheers

--
PA, Onnay Equitursay
http://alt.textdrive.com/