1

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.