Using a string as a variable name

I want to draw buttons in a grid formation for a level select screen. This feels super trivial but I can't figure it out.

I have my button images loaded in a table:

> 	sprites = {}
> 	sprites.level1 = playdate.graphics.image.new('sprites/level1.png')
> 	sprites.level2 = playdate.graphics.image.new('sprites/level2.png')
> 	sprites.level3 = playdate.graphics.image.new('sprites/level3.png')

Then I want to draw them in a next to each other using a loop in the update event:

	-- Draw buttons
   	for i = 1, 3 do
        	varName = ("sprites.level" .. i)
        	varName:draw(208 + (16*i), 56)
    	end

I guess this doesn't work because varName is a string? Is there a way to convert it? Obviously I plan on having way more than 3 levels eventually.

I'm realtively new to game development (please be gentle with me) and despite googling this problem on other Lua forums I can't get my head around it. Please explain like I'm 5.

I would advise to use the gridview for this. It takes care of a lot of things needed to do this well: layout, button presses, selection, wrapping, etc.

Take a look at the gridview example which contains two grid views and reduce it to just the one you want.

Otherwise, if you want to do it yourself. Something more like this:

sprites = {}
sprites[1] = playdate.graphics.image.new('sprites/level1.png')
sprites[2] = playdate.graphics.image.new('sprites/level2.png')
sprites[3] = playdate.graphics.image.new('sprites/level3.png')

for i = 1, 3 do
       sprites[i]:draw(208 + (16*i), 56)
end

Wow, that was simple!

Thank you for the quick reply. I'm off to learn about gridviews!

1 Like

Always try to keep things as simple as possible!

To answer your syntax question: in your code, varName is a string, but you're trying to invoke methods on it as though it were an image. You're missing the step of retrieving the image object from the table:

-- Draw buttons
for i = 1, 3 do
  varName = ("sprites.level" .. i)
  sprites[varName]:draw(208 + (16*i), 56)
end
1 Like