If you are looking to assign data from a JSON string to tables, then the easiest way would loop through them, as you had initially suggested, but first you’d need to fix that JSON (as it isn’t valid as is) and then make changes to your loop too.
First, if you are going to create units/characters like that, i.e. loading them from a JSON string, then you should have all information required for creating them in said string. For instance, what if there is a character that doesn’t have 100 hp? You’d have to add conditional statements to the loop, but you could just add a new entry to the JSON for hp.
Also, you could just use JSON arrays for “skill” entry. Since you are using “1” and “2” keys, why not just store these as array entries 1 and 2? Finally, why not just store “img”, “width” and “height” in the string too? If you want to make things easier for you, then just throw them in and be happy.
So, the first thing I’d do is reformat your data to something like:
[
{
"name": "musketeer",
"id": "hero",
"hp": "100",
"img": "img/local/path/musketeer.png",
"width": "40",
"height": "30",
"skill":[
{
"name": "test_skill_1_musketeer",
"description": "desc_skill_1_musketeer",
"doing": "-hp"
},
{
"name": "test_skill_2_musketeer",
"description": "desc_skill_2_musketeer",
"doing": "+hp"
}
]
}
]
Now, since you know the data structure of your JSON string, you can easily write a loop that will wrap things up nicely. However, you should not make changes to the original table like you do in your proposed loop, but instead:
local json = require( "json" )
-- Presuming the JSON data is stored in a file called "data.json" in the project root.
local path = system.pathForFile( "data.json" )
local file, errorString = io.open( path, "r" )
local contents = file:read( "*a" )
local sampleData = json.decode( contents )
io.close( file )
local unit = {}
for i = 1, #sampleData do
local t = sampleData[i]
unit[i] = display.newImageRect( t.img, t.width, t.height )
unit[i].name = t.name
unit[i].id = t.id
unit[i].hp = t.hp
unit[i].skill = {}
for j = 1, #t.skill do
unit[i].skill[j] = {}
unit[i].skill[j].name = t.skill[j].name
unit[i].skill[j].description = t.skill[j].description
unit[i].skill[j].doing = t.skill[j].doing
end
end
And now you have access to all units you’ve created as well as their original data values. Now, you could go even more streamlined and automate this entire process inside the loop without needing to explicitly assign a single variable, but this will get you started.