Виділення підрядків

Lua:
Виділення підрядків

How to: (Як це зробити:)

In Lua, you can extract substrings using the string.sub function.

local text = "Привіт, як справи?"
local part = string.sub(text, 1, 7)
print(part)  -- Outputs: Привіт,

Sample output:

Привіт,

You can also work with negative indices to count from the end of the string.

local text = "Привіт, як справи?"
local part = string.sub(text, -6, -2)
print(part)  -- Outputs: справ

Sample output:

справ

Deep Dive (Поглиблений Аналіз)

Lua supports various string manipulation functions; string.sub is one among them and has been a part of the language from its early versions. It’s a straightforward and efficient way to interact with strings.

Alternatives include using string.match with patterns. This method offers more flexibility for complex substring extractions.

local text = "Привіт, як справи?"
local part = string.match(text, "як")
print(part)  -- Outputs: як

Implementation-wise, Lua strings are immutable, meaning once created, they can’t be changed. When you extract a substring, Lua creates a new string rather than altering the original.

See Also (Додатково)