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.

4
  • 2
    Is you goal to access individual characters or character spans of the string? Commented Jan 1, 2017 at 10:44
  • 1
    Show us the equivalent C# code that you're trying to accomplish in lua. Commented Jan 1, 2017 at 11:05
  • 1
    Possible duplicate of Lua - convert string to table Commented Jan 1, 2017 at 11:33
  • 1
    To 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. Commented Jan 1, 2017 at 11:42

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.