1

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.

LordW4R10CK
  • 11
  • 1
  • 4

2 Answers2

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