Kevin Gregory
Kevin Gregory

Reputation: 89

Parse String in Lua

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]

Upvotes: 1

Views: 5166

Answers (4)

James Penner
James Penner

Reputation: 81

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 :)

Upvotes: 0

exploitr
exploitr

Reputation: 793

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

Upvotes: 0

lhf
lhf

Reputation: 72312

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

Upvotes: 1

MrHappyAsthma
MrHappyAsthma

Reputation: 6522

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'

Upvotes: 0

Related Questions