Page 1 of 1

"Attempt to index global x a (a nil value)" error

Posted: Tue Apr 04, 2017 1:30 pm
by MichaelShort
What I'm trying to do is make the variable x for the textbutton, so that I can continue positioning and sizing x after I've created it. I'm using this https://love2d.org/wiki/Easy_GUI_System for the GUI.

One of the solutions I've tried using:

Code: Select all

for i=1, 3 do
	x = "button"..i
	TextButton:new(x)
	x.position = {10, 10}
end
and I've tried using:

Code: Select all

for i=1, 3 do
	x = TextButton:new("button"..i)
	x.position = {10, 10}
end
Sorry for being confusing and thanks for any help.

Re: "Attempt to index global x a (a nil value)" error

Posted: Tue Apr 04, 2017 2:24 pm
by DireMitten
Hmm. Seems like the second one should work. Could you try with this, and tell us what the console prints? You can run Love2D games with the console just by dragging and dropping your project folder onto lovec.exe

Code: Select all

for i=1, 3 do
	print(i, "button" .. i)
	x = TextButton:new("button"..i)
	print(x, x.position)
	x.position = {10, 10}
	print(x.position)
end

Re: "Attempt to index global x a (a nil value)" error

Posted: Wed Apr 05, 2017 5:04 am
by yetneverdone
I think you should use reference the x variable as local, since each iteration in the for loop would override it.

Code: Select all

for i=1,3 do
	local x = "button"..i
	TextButton:new(x)
	x.position = {1,1}
end

Re: "Attempt to index global x a (a nil value)" error

Posted: Wed Apr 05, 2017 12:58 pm
by MichaelShort
@DireMitten, the output prints "1 Button1" and then it errors again with "attempt to index global x (a nil value)."

@yetneverdone, that solution also outputs "attempt to index global x (a nil value)."

Re: "Attempt to index global x a (a nil value)" error

Posted: Wed Apr 05, 2017 1:38 pm
by Lucyy
Could you post your code? I believe it'd be easier to find the problem that way

Re: "Attempt to index global x a (a nil value)" error

Posted: Wed Apr 05, 2017 2:07 pm
by davisdude
To me, it looks like the library sets the variable to whatever is passed as the string. So you would access it using something like this:

Code: Select all

x = _G["button" .. i]
x.position = { 1, 1 }

Re: "Attempt to index global x a (a nil value)" error

Posted: Wed Apr 05, 2017 3:01 pm
by yetneverdone
MichaelShort wrote: Wed Apr 05, 2017 12:58 pm @DireMitten, the output prints "1 Button1" and then it errors again with "attempt to index global x (a nil value)."

@yetneverdone, that solution also outputs "attempt to index global x (a nil value)."
It has to do with the textbutton library. Could you show us the "new" function of that?

Re: "Attempt to index global x a (a nil value)" error

Posted: Thu Apr 06, 2017 12:53 pm
by MichaelShort
Davisdude's solution worked, thanks for the help.