如何使Lua中的字符串包含随机字符



我很好奇如何在Lua中将随机字符串打印到输出中,我想知道这是否适用于字符串。因为我知道可以使用Lua中调用的函数生成随机数。数学Random((,但我不知道如何使字符串随机。如何使字符串中的字符随机打印到输出?

-- I want to print out random characters in a string to the consoles output
local Number = math.random(1,80) -- prints out a number 1-80
print(Number)

大写字母在string.char(math.random(65, 90))中,可以使用另一种字符串方法进行延迟降低。。。

local randuppercase = string.char(math.random(65, 65 + 25))
local randlowercase = string.char(math.random(65, 65 + 25)):lower()
print(randlowercase, randuppercase)
-- Example output: g    W

如果没有字符串方法lower((,则lowercases从…开始

local randlowercase = string.char(math.random(97, 97 + 25))
print(randlowercase, randlowercase:upper())
-- Sample output: c    C

另一个可能的解决方案是做得更像老派。。。

local chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" -- The Char Library
local rint = math.random(1, #chars) -- 1 out of length of chars
local rchar = chars:sub(rint, rint) -- Pick it
print(rint, rchar)
-- Sample Output: 12    L

最新更新