Guidelines for using string. Len() in Lua

Time:2021-10-24

preface

Today is Sunday. I won’t waste your brain cells. I’ll directly list a relatively simple function in the string family. Although the function is simple, it is very useful and frequently used. I don’t say much nonsense. Let’s look at the usage of the function directly.

content

string.len()
Prototype: string. Len (s)
Explanation: returns the length of the given string. If the string contains’ \ 0 ‘, it will also be counted as one character.

Usage
First create a new file, name the file lentest.lua, and then write the following code:
–A regular string

?
1
2
3
local sourcestr = "This is a rainy day!"
local sourcelen = string.len(sourcestr)
print("\nthe len of sourcestr is "..sourcelen)

–String containing ‘\ 0’

?
1
2
3
local str = "Hello Lua \000 What?"
local strlen = string.len(str)
print("\nthe len of str is "..strlen)

–Put it another way

?
1
2
local strlen_new = str:len()
print("\nthe len of str is "..strlen_new)

Operation results

Guidelines for using string. Len() in Lua

summary

This function will also count the number of ‘\ 0’ in the string, which is different from C language. This should be noted
The third group of tests is to review another way of writing all functions in the string family. In fact, I have summarized it before, but I’ll consolidate it here again today