Search code examples
for-loopluainsertlua-table

Using a for loop with table.insert


I have a large number of names and stats that I want to put into a table. I have the variables laid out in format below:

enemyname1 = "Evil Frog"

enemyhealth1 = 10

I was hoping there would be a faster way to put them all in than doing it all by hand. Below is my last unsuccessful attempt to do that.

for i = 1,enemytotal do
table.insert(name,i,enemyname .. i)
end

Solution

  • I'd recommend to change your data representation altogether.

    Consider storing the state of an enemy inside a table:

    local enemy1 = {
        name = "Evil Frog",
        health = 10,
    }
    print(enemy1.name)    --> Evil Frog
    print(enemy1.health)  --> 10
    

    Now, rather than storing the enemies in stand-alone variables, let's put them into a table:

    local enemies = {
        {
            name = "Evil Frog",
            health = 10,
        },
        {
            name = "Biggus Froggus",
            health = 100,
        },
    }
    print(enemies[1].name)  --> Evil Frog
    print(enemies[2].name)  --> Biggus Froggus
    

    Since all enemies are in one place it makes easier implementing any iterative actions for all of them:

    local names = {}
    for i, enemy in pairs(enemies) do
        table.insert(names, enemy.name)  -- or: names[i] = enemy.name
    end
    print(names[1])  --> Evil Frog
    print(names[2])  --> Biggus Froggus
    

    What's left is a question of whether enemies table describes the active enemies in game world or enemy types that can show up. Depending on the answer and your needs next potential step may be to write set of functions that create enemies according to some templates and generally move towards Object-Oriented Programming-like code. Possibly using classes implemented with metatables.

    The answer to your specific question is in the comment: you can use _G. Refer to 2.2 - Environments and the Global Environment for detailed explanation.