1

我目前正在编写一个 Lua 脚本。在那里,我想要一个变量名,它与越来越多的数字连接。

示例:Q0001,Q0002,Q0003,...,Q9999

我的以下脚本是:

local rnd = math.random (0,9999)
local Text = ""
print(rnd)
if rnd > 0 and rnd < 10 then
    --Add Nulls before Number and the "Q"
    Text = Q000 .. rnd
elseif rnd >= 10 and rnd < 100 then
    --Add Nulls before Number and the "Q"
    Text = Q00 .. rnd
elseif rnd >= 100 and rnd < 1000 then
    --Add Null before Number and the "Q"
    Text = Q0 .. rnd
elseif rnd >= 1000 then
    --Add "Q"
    Text = Q .. rnd
end
print(Text)

逻辑上我把它放到一个函数中,因为它只是我程序的一部分。稍后在程序中,我喜欢使用变量获取信息,因为变量的乘积Q###是我编写的表。我解决问题的第二个想法是将其转换为文本,但后来我不知道如何将其转换为声明。

编辑 15 年 4 月 4 日 19:17:也让它更清楚。我希望 Text 位于我之前设置的表格的脚本结束之后。所以我可以说Text.Name例如

4

1 回答 1

3

string.format与填充格式说明符一起使用:

就一行:

Text = ("Q%04d"):format( rnd )
-- same as Text = string.format( "Q%04d", rnd )

不要创建这么多表,而是使用具有上述值作为键/索引的单个表:

t = {
    Q0001 = "something",
    Q0002 = "something",
    Q0013 = "something",
    Q0495 = "something",
    -- so on
}
于 2015-04-04T10:40:09.107 回答