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.
Asked
Active
Viewed 3,050 times
1
-
2Is you goal to access individual characters or character spans of the string? – Marc Balmer Jan 01 '17 at 10:44
-
1Show us the equivalent C# code that you're trying to accomplish in lua. – greatwolf Jan 01 '17 at 11:05
-
1Possible duplicate of [Lua - convert string to table](http://stackoverflow.com/questions/20423406/lua-convert-string-to-table) – Wiktor Stribiżew Jan 01 '17 at 11:33
-
1To get single character at position i (1-based), use `str:sub(i,i)`. The is no opposite operation (to modify single character inside a string), as Lua strings are immutable. – Egor Skriptunoff Jan 01 '17 at 11:42
2 Answers
1
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.

John
- 10,165
- 5
- 55
- 71
0
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

Luiz Menezes
- 749
- 7
- 16
-
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. – Luiz Menezes Jan 04 '17 at 20:27