2024年6月10日发(作者:)

Lua中的

函数用于格式化字符串。它接受一个格式化字符串作为第

一个参数,后跟零个或多个要替换的值,并返回格式化后的字符串。

格式化字符串中可以包含占位符,用来指定要替换的值的位置和格式。以下是一

些常用的占位符:

%s

:用于替换字符串。

%d

:用于替换整数。

%f

:用于替换浮点数。

%c

:用于替换一个字符。

%%

:表示一个百分号字面量。

下面是一些示例来说明

的用法:

local name = "Alice"

local age = 25

local height = 1.65

local formattedString = ("My name is %s, I am %d years old

and %.2f meters tall.", name, age, height)

print(formattedString)

-- 输出:My name is Alice, I am 25 years old and 1.65 meters tall.

local pi = 3.14159

local formattedNumber = ("Pi is approximately %.2f.", pi)

print(formattedNumber)

-- 输出:Pi is approximately 3.14.

local char = "A"

local formattedChar = ("The first letter of the alphabet is %c.",

char)

print(formattedChar)

-- 输出:The first letter of the alphabet is A.

local percentage = 0.75

local formattedPercentage = ("The percentage is %.2f%%.",

percentage * 100)

print(formattedPercentage)

-- 输出:The percentage is 75.00%.

可以根据具体的需求使用不同的占位符和格式选项来进行字符串的格式化。详细

的格式化选项可以参考Lua官方文档中的字符串格式化部分。