如何在 lua 中使用字符串作为变量名
How to use string as variable name in lua
拜托,我在 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
问题是,它发送的是字符串而不是纹理数据。
打印 hh 时,它显示:_1_1_cell._2_2_grid.wall.texture,这是正确的,直接使用而不是 hh 时有效。
所以问题是,如何转换字符串以使其加载我需要的内容?
谢谢。
你可以使用 _G[str]
:
local t = _G['_'..rr..'_'..tt..'_cell']['_'..oo..'_'..pp..'_grid'].wall.texture
不过,我真的会重新考虑您存储数据的方式。 正确使用数组会给你(类似的东西):
local cell = cells[rr][tt]
local grid = cell[oo][pp]
local texture = grid.wall.texture
拜托,我在 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
问题是,它发送的是字符串而不是纹理数据。 打印 hh 时,它显示:_1_1_cell._2_2_grid.wall.texture,这是正确的,直接使用而不是 hh 时有效。 所以问题是,如何转换字符串以使其加载我需要的内容? 谢谢。
你可以使用 _G[str]
:
local t = _G['_'..rr..'_'..tt..'_cell']['_'..oo..'_'..pp..'_grid'].wall.texture
不过,我真的会重新考虑您存储数据的方式。 正确使用数组会给你(类似的东西):
local cell = cells[rr][tt]
local grid = cell[oo][pp]
local texture = grid.wall.texture