Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua 如何创建以递增数字连接的变量名_Lua_Variable Names - Fatal编程技术网

Lua 如何创建以递增数字连接的变量名

Lua 如何创建以递增数字连接的变量名,lua,variable-names,Lua,Variable Names,我目前正在编写一个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

我目前正在编写一个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)
local rnd=math.random(09999)
本地文本=“”
打印(rnd)
如果rnd>0且rnd<10,则
--在数字和“Q”之前添加空值
Text=Q000。。rnd
如果rnd>=10且rnd<100,则
--在数字和“Q”之前添加空值
Text=Q00。。rnd
如果rnd>=100且rnd<1000,则
--在数字和“Q”之前添加Null
Text=Q0。。rnd
如果rnd>=1000,则
--加上“Q”
Text=Q。。rnd
结束
打印(文本)
从逻辑上讲,我把它放在函数中,因为它只是我程序的一部分。在以后的程序中,我喜欢用变量获取信息,因为变量的乘积
Q###
是我已经编程的一个表。我解决这个问题的第二个想法是将其转换为文本,但我不知道如何将其转换为声明


编辑04/04/15 19:17:太清楚了。我希望文本位于我之前设置的表的脚本末尾之后。因此我可以说
Text.Name
例如使用
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
}

或者只使用一个普通数组。好的,我用谷歌搜索了string.format函数,但是只有一个带有参数的列表。所以我真的不明白你在这里向我解释了什么。我在控制台中测试了您的示例之后,给出了名称Q#####,但是应该是nil,因为我还没有声明变量。我得到了以下错误:org.luaj.vm2.LuaError:C:\…'FileName'.lua:46应该是表索引,得到了表堆栈回溯:C:\…'FileName'.lua:46:in main chunk[Java]:in?在org.luaj.vm2.LuaClosure.org.luaj.vm2.LuaClosure.execute(未知源)在org.luaj.vm2.LuaClosure.org.luaj.vm2.LuaClosure.onInvoke(未知源)在org.luaj.vm2.LuaClosure.invoke(未知源)在lua.main(未知源)在lua.processScript(未知源)调用(未知源)