Recently, I decided to try out Lua/Love2D. I have decided to create a small game, and I am working on a way to store NPCs and data belonging to them. How it works is quite simple: each NPC has a memory slot where their identifiers are stored. To aid this, I decided to research dynamic variables. I implemented them, but it doesn't work. I get the error "attempt to index a string value" The code is here, and the error is on line 13. What am I doing wrong?
npcmem01 = {visible="false", x=0, y=0, npctype="", weapon=0}
npcmem02 = {visible="false", x=0, y=0, npctype="", weapon=0}
npcmem03 = {visible="false", x=0, y=0, npctype="", weapon=0}
npcmem04 = {visible="false", x=0, y=0, npctype="", weapon=0}
local vars = {"npcmem"}
function SpawnNPC(npctype, x, y, slot)
if npctype == "Civilian" then
("npcmem" .. slot).npctype = "Civilian"
end
end
To do that you want (dynamic variable name) you need to use environment table _G
:
_G["npcmem" .. slot].npctype = "Civilian"
however, you really should use a simple array:
npcs = {};
function SpawnNPC(npctype, x, y, slot)
local tmp = {visible="false", x=0, y=0, npctype="", weapon=0}
if npctype == "Civilian" then
tmp.npctype = "Civilian"
npcs[slot] = tmp
end
end