Enumerations within Lua?

Bicentric picture Bicentric · Sep 24, 2013 · Viewed 8.4k times · Source

I have a new question for you all, I am wondering if you're able to do enumartions within Lua, I am not sure if this is the correct name for it, the best way I can explain this is if I show you an example using PAWN (if you know a C type language it will make sense).

#define MAX_SPIDERS 1000

new spawnedSpiders;

enum _spiderData {
    spiderX,
    spiderY,
    bool:spiderDead
}

new SpiderData[MAX_SPIDERS][_spiderData];

stock SpawnSpider(x, y)
{
    spawnedSpiders++;
    new thisId = spawnedSpiders;
    SpiderData[thisId][spiderX] = x;
    SpiderData[thisId][spiderY] = y;
    SpiderData[thisId][spiderDead] = false;
    return thisId;
}

So that's what it would look like in PAWN, however I don't know how to do this in Lua... This is what I got so far.

local spawnedSpiders = {x, y, dead}
local spawnCount = 0

function spider.spawn(tilex, tiley)
    spawnCount = spawnCount + 1
    local thisId = spawnCount
    spawnedSpiders[thisId].x = tilex
    spawnedSpiders[thisId].y = tiley
    spawnedSpiders[thisId].dead = false
    return thisId
end

But obviously it gives an error, do any of you know the proper way of doing this? Thanks!

Answer

Yu Hao picture Yu Hao · Sep 24, 2013

I don't know about PAWN, but I think this is what you mean:

local spawnedSpiders = {}

function spawn(tilex, tiley)
    local spiderData = {x = tilex, y = tiley, dead = false} 
    spawnedSpiders[#spawnedSpiders + 1] = spiderData
    return #spawnedSpiders
end

Give it a test:

spawn("first", "hello")
spawn("second", "world")

print(spawnedSpiders[1].x, spawnedSpiders[1].y)

Output: first hello