How would I convert a string to a table of letters?

Hey Devforumers!

I know this is probably super simple and I’m being dumb right now, but how would I take a string and convert it into a table/array where each entry in the table is a character of the string?

Example:

Str:

local string = "Abc123 !@#"

Finished Table:

local tableOfChars = {
    "A",
    "b",
    "c",
    "1",
    "2",
    "3",
    "\s",
    "!",
    "@",
    "#"
}

If you really want to know what this is for: I’m making a lexer in Lua for an already existing language.

2 Likes

This isn’t an efficient way, but it’s short and if you only need to run it once in a while it will be fine.

local function toTable(s)
   local t = {}
   s:gsub(".", function(c) table.insert(t, c) return c end)
   return t
end
3 Likes

Yeah, I’m using this as a function where I feed in the script’s contents and the lexer can loop over each entry in the table and form phrases for the interpreter to process.

The simplest way I can think of would be to use string.split, which returns a table itself.
The function splits the string wherever a specified expression occurs, so if you use an empty string it will split every character.

local s = "abc 123"
local t = s:split("")
table.foreachi(t, print)
--[[
1 a
2 b
3 c
4
5 1
6 2
7 3
]]--
15 Likes

Is there anyway to change the numbers into the actual value?

toNumber(--[[put your string here]]--)