Search code examples
stringlualove2d

How to use string as variable name in lua


Please, i got code in lua(love2d):

nn = love.graphics.newImage'texture.png'

_1_1_cell = {
    _2_2_grid = {
        wall = { 
            texture = nn 
        }
    }
}

function drawGrid( ... )
    local rr, tt, oo, pp = 1, 1, 2, 2
    local hh = '_'..rr..'_'..tt..'_cell._'..oo..'_'..pp..'_grid.wall.texture'
    return
    --this should draw texture at certain position
    texture.quad( hh, {x,y}, {x,y}, {x,y}, {x,y} )
end

problem is, it sends string instead of the texture data. when hh is printed, it displays: _1_1_cell._2_2_grid.wall.texture, which is correct and works when used directly instead of hh. so question is, how to convert the string to make it load what i need? thanks.


Solution

  • You can use _G[str] for that:

    local t = _G['_'..rr..'_'..tt..'_cell']['_'..oo..'_'..pp..'_grid'].wall.texture
    

    I'd really rethink the way you store data, though. Using arrays properly would give you (something like):

    local cell = cells[rr][tt]
    local grid = cell[oo][pp]
    local texture = grid.wall.texture