I was wondering how I use a string value as an array in Lua. I do know how to use it in languages like C#, but I don't know how to do it in Lua.
2 Answers
string.sub(yourString,i,j) or just sub(yourString,i,j) where i = j to get just one character in the string. Remember that Lua is 1-indexed, not 0-indexed like C#. Have a look at the Lua string documentation for more details.
Comments
You can get the String metatable and change the metamethod __index to return the character on a given position... the code below does exactly that.
getmetatable('').__index = function(str,i) return string.sub(str,i,i) end
--example
string = "dog"
print(string[3])
-- Output: g
1 Comment
Luiz Menezes
I tried to use the __newindex to make it read/write, but turn out that the first argument in the function is a string, and thus is passed by copy... should it got passed by reference it would be possible to change it.
str:sub(i,i). The is no opposite operation (to modify single character inside a string), as Lua strings are immutable.