Search code examples
lualua-tablelove2d

How to reference an object in a table in Lua by its name


This seems like a very straightforward question, but I haven't been able to turn up an answer. I am adding game objects to a table in Lua like this:

local lock = GameObject {
 -- object values and methods
table.insert(objects, lock)

But despite a lot of google searching and reading through the Lua documentation, I cannot figure out how to reference these objects by their names. I think it's because there is a very specific syntax to do so. If anyone could help me out, I would greatly appreciate it. Thanks!


Solution

  • You might want to do something like this instead of table.insert. Objects will still be a table.

    objects = {}
    objects.lock = {}
    objects.lock2 = {}
    

    If you then execute

    for key, value in pairs(objects) do
      print(key,value)
    end
    

    You will get the output

    lock2   table: 0x1af3310
    lock    table: 0x1af3870
    

    Further explanation

    In you question(not the solution above) lock is only the variable name given to it, it is not the name of the index.

    In this code snippet, you can see that the items being inserted into objects do not have the variable name recorded within objects. objects is storing an int as the key, and then the inserted table as the value.

    objects = {}
    local lock = {}
    local lock2 = {}
    
     -- object values and methods
    table.insert(objects, lock)
    table.insert(objects, lock2)
    
    for key, value in pairs(objects) do
      print(key,value)
      print(type(value))
    end
    

    prints

    1   table: 0x131b590
    table
    2   table: 0x131b540
    table
    

    test it on repl