Визначення довжини рядка

Lua:
Визначення довжини рядка

Що та Навіщо?

Finding the length of a string means getting the number of characters it contains. Programmers do this to validate input, process text data, or just to manage string data efficiently.

How to:

Як це зробити:

-- Basic usage
local str = "Привіт"
print(#str)  -- Output: 6

-- Storing length in a variable
local len = #str
print(len)   -- Output: 6

-- Working with strings in tables
local greetings = {"Привіт", "Hello", "Bonjour"}
for _, greeting in ipairs(greetings) do
    print(#greeting)
end
-- Output:
-- 6
-- 5
-- 7

Deep Dive

Поглиблений Аналіз

In older programming languages, strings were different and getting their length was not this straightforward. Lua uses a simple # operator to find a string’s length. It counts the number of bytes, which, for UTF-8 encoded strings, may differ from the expected character count. It’s a direct operation with no extra frills — fast and memory-efficient.

If you’re dealing with multi-byte characters, as in UTF-8, you may need a different approach to count actual characters since the # operator may not give accurate results. In those cases, functions from libraries like ’luautf8’ can help:

local utf8 = require('lua-utf8')
print(utf8.len("Привіт"))  -- Output: 6

This library handles multi-byte characters correctly. Implementation-wise, finding the length of a string is a matter of iterating over the string and counting elements, which languages handle differently. In Lua, simplicity is key, keeping the language approachable and code readable.

See Also

Дивіться також

For more on strings in Lua:

UTF-8 and string manipulation in Lua: