1

I've found a lot of ways to split a string at a comma in Lua, but that's not quite what I'm looking for. I need to be able to do the following: I have the argument ABC being in as a string, and I need to be able to extract just the A, B, and the C. How do I do this? I keep hoping something like this will work:

x = tostring(ABC)
x[1]
x[2]
x[3]
1
  • Is there some kind of fixed format? I.e. is it always three characters? Or is there some kind of delimiting character? Also what version of Lua are you using? Commented May 30, 2018 at 11:07

4 Answers 4

2

You can also set a call metamethod for strings:

getmetatable("").__call = string.sub

Then this works:

for i=1,4 do
        print(i,x(i),x(i,i))
end
Sign up to request clarification or add additional context in comments.

1 Comment

1

Without confusing metatables:

function getCharacters(str)
local x = {}
for i=1, str:len(), 1 do
table.insert(x, str:sub(i, i))
end
return x
end

With this function, no matter how long your string is, you will always have a table filled with it's characters in it :)

Comments

0

If you just want to get the substrings of an index, this should work in most version of Lua:

x = 'ABC'
print (string.sub(x, 1, 1))  -- 'A'
print (string.sub(x, 2, 2))  -- 'B'
print (string.sub(x, 3, 3))  -- 'C'

In Lua 5.1 onward, according to this doc, you can do the following:

getmetatable('').__index = function(str,i) return string.sub(str,i,i) end

x = 'ABC'
print (x[1])  -- 'A'
print (x[2])  -- 'B'
print (x[3])  -- 'C'

2 Comments

It's better to preserve old __index metamethod for strings: function(str,i) return type(i)=="number" and str:sub(i,i) or str[i] end
In my previous comment str[i] should be replaced with string[i] to avoid stack overflow :-)
0

It's quite easy. Just iterate.

(Assume you're using version 5.1 of Lua)


Code :

str = "xyz"
for i = 1, #str do
    local c = str:sub(i,i)
    print(c)
end

Output :

$lua main.lua
x
y
z

Try it online!


Or, as @tonypdmtr said in comment :

for s in s:gmatch '.' do print(s) end

1 Comment

Or simpler: for s in s:gmatch '.' do print(s) end

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.