I saw on the Lua mailing list a cool suggestion for string indexing.
The gist is to make a simpler syntax for pulling out an individual character from a string. For example, if you want to find the first character you currently do:
This is a little ugly. Now if you add the following code to the initialization of your Lua code:
What that does is add a metamethod for handling the indexing into any string (since all Lua strings share the same metatable).
Now you can do this:
[EDIT]
Modified per discussion below, so the discussion may not make a heap of sense.
The gist is to make a simpler syntax for pulling out an individual character from a string. For example, if you want to find the first character you currently do:
a = "nick"
print (string.sub (a, 1, 1)) --> n
This is a little ugly. Now if you add the following code to the initialization of your Lua code:
getmetatable ("").__index = function (str, i)
if (type (i) == "number") then
return string.sub (str, i, i) -- index into str
end -- if
return string [i] -- fallback (eg. string.match)
end -- function
What that does is add a metamethod for handling the indexing into any string (since all Lua strings share the same metatable).
Now you can do this:
a = "nick"
print (a [1]) --> n
[EDIT]
Modified per discussion below, so the discussion may not make a heap of sense.