lua substring | get char from from index

To get a substring or a character from a Lua string based on an index, you can follow these steps:

  1. First, define the string you want to extract the substring or character from.
  2. Determine the index of the substring or character you want to retrieve. In Lua, string indices start from 1.
  3. Use the string.sub() function to extract the substring or character from the string. Pass the string as the first argument, the starting index as the second argument, and optionally the ending index as the third argument if you want to extract a substring. If you only want to retrieve a single character, use the same index for the starting and ending arguments.
  4. Assign the result of the string.sub() function to a variable if you want to store the extracted substring or character for further use.

Here's an example that demonstrates these steps:

local myString = "Hello, Lua!"

-- Retrieve a substring from index 3 to index 8
local substring = string.sub(myString, 3, 8)

-- Retrieve a single character at index 10
local character = string.sub(myString, 10, 10)

print(substring)  -- Output: llo, L
print(character)  -- Output: u

In this example, the string.sub() function is used to extract a substring from index 3 to index 8, resulting in the string "llo, L". Additionally, the function is used to retrieve a single character at index 10, resulting in the character "u". The print() function is then used to display the extracted substring and character on the console.