Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

Get Variable by adding a new number in a for loop?

Asked by 5 years ago

Is this even possible? For example say I have this code

local part1 = "hi"
local part2 = "hello"

for i = 1, 2 do
print("part"..i)
end

So basically I want it to print the Variable but that will literally just print "part1" and "part2". How can I make it print "hi" and "hello"??

0
To the best of my knowledge, this is not possible. You could use a dictionary with string indices, though. User#25115 0 — 5y

1 answer

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

There is not a really simple way to do this in Lua. Your best option is to have a table with string indices.


Here's an example:

local tbl = {
    ["part1"] = "hello";
    ["part2"] = "hello2";
    ["part3"] = "hello3";
}
for i = 1, 3 do
    print(tbl["part"..i])
end

kingdom5 also suggested this as an option. However, it's better to use a table.


I hope this helps. Have a great day scripting!

0
Technically you can with `getfenv` but that's just a hypothetical. Using tables is much better. ScriptGuider 5640 — 5y
0
Yeah, kingdom5 mentioned that, but said it was not a good idea. User#25115 0 — 5y
Ad

Answer this question