5

I have a new question for you all.

I am wondering if you're able to do enumerations 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!

LoneWanderer
  • 3,058
  • 1
  • 23
  • 41
Bicentric
  • 1,263
  • 3
  • 12
  • 12
  • 1
    This conversation doesn't solve the issue given in title "How to do enumerations in LUA?". Could it be modified to: "How to translate the PAW example to LUA?" – Akhneyzar Oct 16 '15 at 14:11

2 Answers2

4

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

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
4

Something like this?

local spawnedSpiders = {}
local spawnCount = 0

function spawn_spider(tilex, tiley)
    spawnCount = spawnCount + 1
    spawnedSpiders[spawnCount] = {
      x = tilex,
      y = tiley,
      dead = false,
    }
    return spawnCount
end

EDIT: Yu Hao was faster than me :)

catwell
  • 6,770
  • 1
  • 23
  • 21
  • Aha that's okay! It's what I was looking for anyway :3 – Bicentric Sep 24 '13 at 14:54
  • 1
    `spawnCount` can be replace with `#spawnedSpiders` – hjpotter92 Sep 24 '13 at 20:13
  • 1
    @hjpotter92 For simplicity, yes, like in Yu Hao's answer. If there is a *lot* of spiders it will be slightly less efficient though because the length operator `#` is `O(log n)`. But the real reason I didn't do it is I wanted to stay close to @Bicentric's code (avoid introducing another concept). – catwell Sep 25 '13 at 08:59