school_guy
school_guy

Reputation: 300

How to create variable names that are concatenated with a increasing number

I am currently programming a Lua script. There I would like to have a variable name which is concatenated with an increasing number.

Example: Q0001,Q0002,Q0003,...,Q9999

My following script for this is:

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)

Logically I put this into a function, because its only a part of my programm. Later in the programm I like to get informations with the variable, because the product of the variable Q### is a table which I have programmed. My second thought to solve the problem was to convert it as a text, but then I don't know how to convert this into a declaration.

Edit 04/04/15 19:17: Too make it more clear. I want that Text stands after the end of the script for a table I set before. So that I can say Text.Name e.g.

Upvotes: 1

Views: 118

Answers (1)

hjpotter92
hjpotter92

Reputation: 80649

Use string.format with padded format specifiers:

Just a single line:

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

Instead of creating so many tables, use a single table with the above values as keys/indexes:

t = {
    Q0001 = "something",
    Q0002 = "something",
    Q0013 = "something",
    Q0495 = "something",
    -- so on
}

Upvotes: 3

Related Questions