Understanding of this algorithm (loop creates gui elements).
3 replies, posted
Hi. I'm trying to understand the following algorithm:
[lua]
local BtnLabels = {"Button 1","Button 2","Button 3"}
for i = 1, 3 do
local Buttons = vgui.Create( "DButton", DFrame )
Buttons:SetText(BtnLabels[i])
// <more code ..>
end [/lua]
At the first iteration it will create a button with the variable-name "Buttons". Then at the next iteration it does the same thing again, using the [B]same[/B] variable-name "Buttons". Why does this work?
And to extend my previous question, how would you access a specific button since they have all the same variable-name?
Here's my best way to describe it
In case you don't know how locals work, think of it as a variable you can only use in that single run of the code. (this isn't exactly how it works but it might be easier to understand)
So on the first run, button it made and anything that needs to be changed is. On the next run, button is forgotten and over written with the new button.
Once the code is ran, you are kinda screwed if you want to change something, your best bet us to write it manually, unless you do not know how many buttons you need.
[editline]21st July 2013[/editline]
I would go into more detail but on my phone :/
[editline]21st July 2013[/editline]
If you do want to change the button later add it a table
Local buttons = {}
For i=1, 3 do
button[i] = vgui.create
Etc
Of course a for-loop has its own scope!! How could I not see this before, arghhh. xD
for i = 1, 3 do
[B]{[/B]
// code
[B]}[/B]
end
And the trick with the table works great. Thank you for your helpful explanation. :)
[CODE]
local Buttons = {}
local Texts = {"Button 1", "Button 2", "Whatever you like"}
for Key, Text in pairs(Texts) do
Buttons[Key] = vgui.Create("DButton")
Buttons[Key]:SetText(Text)
--More Code
end
[/CODE]
Sorry, you need to Log In to post a reply to this thread.