This code is "working too hard" to find the entity. You are not taking advantage of the benefit provided by tables' keys. (i.e. you are using integer keys and trying to iterate through to find your named entity)
Here is my cleanup of your code to make it work, without straying too much from the pattern you are attempting:
Code: Select all
ent = {}
function ent.create( name, id, x, y, type, r, g, b )
ent[name] = {name=name, id = id + 1, x=x, y=y, type=type, r=r, g=g, b=b}
end
ent.create("apple", 0, 50, 50, "consumable", 150, 50, 50)
function ent.getID( ent_name )
if not ent[ent_name] then
print(" Error: " .. ent_name .. " is not a valid entity.")
return false
end
return ent[ent_name].id
end
print( tostring(ent.getID("apple")) )
Edit:
To answer your question, the reason your code wasn't working is that table.insert results in *integer indexed* tables, and your search logic was trying to find your entity making the (incorrect) assumption that you had stored it with your "name" as a key.
Edit 2:
Actually, after looking at it some more, it looks like your pairs loop is actually correct, but then you're looping through the "v" table using the # operator (but that table is actually k,v pairs -- not indexed). At any rate, your lookup code had a really weird structure that is hard on my brain. That's why I simplified it